[
{ "_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 = "[rn { "_id" : "BrownHair", "Count" : 1 },rn {"_id" : "BlackHair" , "Count" : 5},rn {"_id" : "WhiteHair" , "Count" : 15}rn]";
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/在这种情况下会是你最好的朋友。