如何将JSON以下转换为C#POCO对象

问题描述

[
  { "_id" : "brownHair","Count" : 1 },{"_id" : "BlackHair","Count" : 5},{"_id" : "WhiteHair","Count" : 15}
]

我想将上面的json转换为如下的C#POCO对象

 public class HairColors
    {
        public int brownHair { get; set; }
        public int BlackHair { get; set; }
        public int WhiteHair { get; set; }       
    }

请注意,我无法更改 POCO和JSON的结构。

解决方法

您可以使用JObject https://dotnetfiddle.net/ydvZ3l

进行一些自定义解析
        string json = "[\r\n  { \"_id\" : \"BrownHair\",\"Count\" : 1 },\r\n  {\"_id\" : \"BlackHair\",\"Count\" : 5},\r\n  {\"_id\" : \"WhiteHair\",\"Count\" : 15}\r\n]";

        var jobjects = JArray.Parse(json);
        foreach(var item in jobjects) {
            // Map them here
            Console.WriteLine(item["_id"]);
            Console.WriteLine(item["Count"]);
        }
// Output
//BrownHair
//1
//BlackHair
//5
//WhiteHair
15
,

我会用这样的东西:

public class MyArray    {
    public string _id { get; set; } 
    public int Count { get; set; } 
}

public class Root    {
    public List<MyArray> MyArray { get; set; } 
}

用法:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 

在这种情况下,https://json2csharp.com/将是您最好的朋友。