使用 JsonSerializer.Deserialize 可能返回空引用

问题描述 投票:0回答:1

尝试反序列化从 Json 文件读取并返回空而不是所需的对象。我正在尝试使用模式弹出窗口中的对象来显示一些产品信息。我在下面列出了当前的代码:

public class Product
{
    public string? Id { get; set; }
    
    public string? Maker { get; set; }
        
    [JsonPropertyName("Img")]
    public string? Image { get; set; }
    
    public string? Url { get; set; }
    
    public string? Title { get; set; }
    
    public string? Description { get; set; }

    public override string ToString() => JsonSerializer.Serialize<Product>(this,
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });
}
public class ProductsController : ControllerBase
{
    //this is where we add the json file product service
    public ProductsController(JsonFileProductService productService)
    {
        ProductService = productService;
    }

    //dereference the products
    public JsonFileProductService ProductService { get; }

    //this method retrieves the products from the json file
    //realize this isn't optimal way just using for testing
    [HttpGet]
    public IEnumerable<Product> Get() => ProductService.GetProducts();
}

public class JsonFileProductService
{
 
    public JsonFileProductService(IWebHostEnvironment webHostEnvironment)
    {
        WebHostEnvironment = webHostEnvironment;
    }

    public IWebHostEnvironment WebHostEnvironment { get; }

    private string JsonFileName => Path.Combine(WebHostEnvironment.WebRootPath,    
    "Data","products.json");
    public IEnumerable<Product> GetProducts()
    {
        using StreamReader jsonFileReader = File.OpenText(JsonFileName);
        return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(),
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });
    }
}

调用 GetProducts:


    void SelectProduct(string productId)
    {
        selectedProductId = productId;
        selectedProduct = ProductService.GetProducts().First(x => x.Id 
        == productId);
    }

Json 格式:

[
  {
    "Id": "string",
    "Maker": "name",
    "img": "https://somedomain.jpeg",
    "Url": "https://domain/",
    "Title": "string of words",
    "Description": "string of words",
    "Ratings": [5, 5]
  },
  {
    "Id": "string",
    "Maker": "name",
    "img": "https://somedomain.jpeg",
    "Url": "https://domain/",
    "Title": "string of words",
    "Description": "string of words",
    "Ratings": [5, 5]
  }
]

尝试添加 PropertyNameCaseInsensitive = true; 仍然返回 null。

c# .net-core system.text.json jsonserializer
1个回答
0
投票

我发现问题是@using Listet.Website.Components。通过将 using 更改为 @using Components,解决了有时产品返回 null 的问题。

© www.soinside.com 2019 - 2024. All rights reserved.