将JSON初始化为C#类将返回null

lokaqttq  于 5个月前  发布在  C#
关注(0)|答案(4)|浏览(74)

我试图将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;
        }

nnsrf1az

nnsrf1az1#

因为
您正在使用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

1bqhqjot

1bqhqjot2#

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

nnvyjq4y

nnvyjq4y3#

如果你有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选项Edit-->Paste Special-->Paste JSON as Classes

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

frebpwbc

frebpwbc4#

使用System.Text.Json;
根据微软官方文档(https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/customize-properties?pivots=dotnet-8-0),“web默认命名策略是camel case”。

JsonSerializerOptions options = new(JsonSerializerDefaults.Web)
    {
        WriteIndented = true
    };

字符串
在.NET 8中,可以指定JSON在序列化/解序列化时可以使用的命名策略

var test  = new HttpResponseMessage
{
    Content = JsonContent.Create(jsonBody, options: new JsonSerializerOptions { DictionaryKeyPolicy = JsonNamingPolicy.CamelCase }),
    StatusCode = httpStatusCode
};

相关问题