将JSON反序列化为C#类时返回null。

6

我试图将一个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<Product>作为“Products”属性的问题 - 如果不起作用,请尝试将其改为ICollection<Product>List<Product>。对于更优雅的解决方案,我相信有一种方法可以设置默认集合实现,但我不知道它是什么。 - eouw0o83hf
我已尝试使用List和ICollection,但不幸的是仍然无法工作。 - Dhawal Dhingra
3个回答

11

原因

您正在使用来自Netwonsoft.Json包的JsonProperty属性,但使用了内置的.NET Core/5反序列化器,它来自于System.Text.Json命名空间。

如何知道?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,我该如何进行反序列化呢? - Dhawal Dhingra
1
然后将属性名称更改为 System.Text.Json 中的“JsonPropertyName”。 - Hazaaa
这解决了这个特定的情况!但在我的情况下,我不得不使用小写字母而不是大写字母来添加 JsonPropertyName 的值。所以,我不得不写成 JsonPropertyName("productName") 而不是 JsonPropertyName("ProductName")。可能是因为 JsonSerializerSettings 指定了 CamelCase,而 JsonPropertyName 应该覆盖它。 - undefined

5
使用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; }
}

1

如果您有JSON响应,只需使用此网站进行转换JSON到C#类

// 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;
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接