[英]How to deserialize this JSON to C# Class
我正在使用從請求返回此json的WebAPI
{
"apps": {
"570": {
"228983": {
"8124929965194586177": "available"
},
"228990": {
"1829726630299308803": "available"
},
"373301": {
"840315559245085162": "available"
},
"373302": {
"688854584180787739": "available"
},
"373303": {
"3675525977143063913": "available"
},
"373305": {
"4435851250675935801": "available"
},
"381451": {
"6984541794104259526": "available"
},
"381452": {
"1442783997179322635": "available"
},
"381453": {
"6878143993063907778": "available"
},
"381454": {
"7824447308675043012": "available"
},
"381455": {
"5681120743357195246": "available"
}
},
"674940": {
"674941": {
"6246860772952658709": "available"
}
}
}
}
它返回一個AppID列表(int),其中包含另一個DepotID列表,其中包含一個ManifestID(鍵),以及是否可用(值)。
我想反序列化到一類上來輕松使用它,但是我無法想象如何做到這一點。 我是C / C ++中的C#新手
您可以使用Newtonsoft.Json NuGet包並將數據反序列化為嵌套字典,如下所示:
var data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, string>>>>>(File.ReadAllText("Data.json"));
為了確保您獲得正確的數據,可以運行以下代碼以將其打印出來:
foreach (var a in data) { Console.WriteLine(a.Key); foreach (var b in a.Value) { Console.WriteLine("\\t" + b.Key); foreach (var c in b.Value) { Console.WriteLine("\\t\\t" + c.Key); foreach (var d in c.Value) { Console.WriteLine("\\t\\t\\t" + d.Key + ": " + d.Value); } } } }
不太確定如何將該數據反序列化為一個類,因為它沒有太多的屬性名稱...
我不確定將其建模為C#類,而沒有屬性名稱超出Json的“ apps”級別,會獲得多少收益,但是您可以這樣做:
使用以下類為您的Json建模:
public class AppIds : Dictionary<string, DepotId> { }
public class DepotId : Dictionary<string, ManifestId> { }
public class ManifestId : Dictionary<string, string> { }
然后您可以使用Newtonsoft.Json這樣做
class Program
{
static void Main(string[] args)
{
string jsonPath = @"c:\debug\data.json";
System.IO.Stream s = new System.IO.FileStream(jsonPath,System.IO.FileMode.Open, System.IO.FileAccess.Read);
AppIds data = JsonConvert.DeserializeObject<Dictionary<string, AppIds>>(File.ReadAllText(jsonPath))["apps"];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.