[英]How can I Convert Below JSON to C# POCO Object
[
{ "_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/將是您最好的朋友。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.