【问题标题】:Deserializing JSON to a C# class returns null将 JSON 反序列化为 C# 类返回 null
【发布时间】:2021-01-25 17:37:08
【问题描述】:

我正在尝试将 JSON 文件反序列化为 c# 类。但是,我的反序列化方法总是返回 null。 我的 JSON 文件如下所示-

{
  "Products": [
    {
      "ProductID": 994,
      "Name": "LL Bottom Bracket",
      "ProductNumber": "BB-7421",
      "ProductCategoryID": 9,
      "ProductCategory": "Bottom Brackets",
      "ProductModelID": 95,
      "Description": "Chromoly steel."
    },
    {
      "ProductID": 995,
      "Name": "ML Bottom Bracket",
      "ProductNumber": "BB-8107",
      "ProductCategoryID": 9,
      "ProductCategory": "Bottom Brackets",
      "ProductModelID": 96,
      "Description": "Aluminum alloy cups; large diameter spindle."
    }
  ]
}

我正在尝试将其序列化为以下类-

public class Product
    {
        [JsonProperty("ProductID")]
        public long ProductId { get; set; }

        [JsonProperty("Name")]
        public string Name { get; set; }

        [JsonProperty("ProductNumber")]
        public string ProductNumber { get; set; }

        [JsonProperty("ProductCategoryID")]
        public long ProductCategoryId { get; set; }

        [JsonProperty("ProductCategory")]
        public string ProductCategory { get; set; }

        [JsonProperty("ProductModelID")]
        public long ProductModelId { get; set; }

        [JsonProperty("Description")]
        public string Description { get; set; }

        [JsonProperty("Color", NullValueHandling = NullValueHandling.Ignore)]
        public string Color { get; set; }
    }
    public partial class Products
    {
        [JsonProperty("Products")]
        public IEnumerable<Product> ProductsProducts { get; set; }
    }

最后,我正在使用此代码对其进行反序列化,但由于某种原因它返回 null。有人可以帮忙吗?

public Products Get()
        {
            var jsonString = IO.File.ReadAllText("ProductsData.json");
            var products = JsonSerializer.Deserialize<Products>(jsonString);
            
            return products;
        }

【问题讨论】:

  • IEnumerable&lt;Product&gt; 用于"Products" 属性可能会出现问题 - 如果不起作用,请尝试将其设为ICollection&lt;Product&gt;List&lt;Product&gt;。对于更优雅的解决方案,我相信有一种方法可以设置默认集合实现,但我不知道它是什么。
  • 我已经尝试过使用 List 和 ICollection 但不幸的是它仍然无法正常工作。

标签: c# json deserialization json-deserialization


【解决方案1】:

原因

您使用的是 Netwonsoft.Json 包中的 JsonProperty 属性,但使用的是 System.Text.Json 命名空间中的内置 .NET Core/5 反序列化器。

我怎么知道? Newtonsoft.Json 没有采用单个字符串的 JsonSerializer.Deserialize 重载,并且 .NET 不包含 JsonPropertyAttribute

这两者不兼容。 .NET 反序列化程序会忽略您的 [JsonProperty("Products")] 属性,在您的 JSON 中找不到名为 ProductsProducts 的属性,因此会为该属性生成 null。


修复

要改用 Newtonsoft.Json 包中的反序列化器,请替换

var products = JsonSerializer.Deserialize<Products>(jsonString);

var products = JsonConvert.DeserializeObject<Products>(jsonString);

这里是你的代码的工作小提琴:https://dotnetfiddle.net/27Tz4t

【讨论】:

  • 谢谢,解决了。但是可以说,由于某种原因我没有使用 Newtonsoft.Json,我是如何反序列化它的?
【解决方案2】:

使用NewtonsoftJson

var products = JsonConvert.DeserializeObject<Products>(jsonString);

使用 System.Text.Json

var products = JsonSerializer.Deserialize<Products>(jsonString);
public partial class Products
{
    [System.Text.Json.Serialization.JsonPropertyName("Products")]
    public IEnumerable<Product> ProductsProducts { get; set; }
}

【讨论】:

    【解决方案3】:

    如果您有 json 响应,请仅使用此站点进行转换 Json to c# class

    // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
        public class Product    {
            public int ProductID { get; set; } 
            public string Name { get; set; } 
            public string ProductNumber { get; set; } 
            public int ProductCategoryID { get; set; } 
            public string ProductCategory { get; set; } 
            public int ProductModelID { get; set; } 
            public string Description { get; set; } 
        }
    
        public class Root    {
            public List<Product> Products { get; set; } 
        }
    
    public Products Get()
            {
                var jsonString = IO.File.ReadAllText("ProductsData.json");
                var products = JsonSerializer.Deserialize<Root>(jsonString);
                
                return products;
            }
    

    或使用 Visual Studio 选项 编辑-->选择性粘贴-->将 JSON 粘贴为类

     public class Rootobject
            {
                public Product[] Products { get; set; }
            }
    
            public class Product
            {
                public int ProductID { get; set; }
                public string Name { get; set; }
                public string ProductNumber { get; set; }
                public int ProductCategoryID { get; set; }
                public string ProductCategory { get; set; }
                public int ProductModelID { get; set; }
                public string Description { get; set; }
            }
    
    
    
    
    public Products Get()
                {
                    var jsonString = IO.File.ReadAllText("ProductsData.json");
                    var products = JsonSerializer.Deserialize<Rootobject>(jsonString);
                    
                    return products;
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      相关资源
      最近更新 更多