正在分析JSON文件C#
本文关键字:文件 JSON | 更新日期: 2023-09-27 18:20:24
我有以下JSON,我想将其解析为C#。我尽量避开外面的图书馆,但如果必须的话,我可以使用它们。现在,我正在使用JavaScriptSerializer方法,根据另一个stackerflow问题的答案从JSON文件进行解析。不幸的是,我可以在参考资料下有任意数量的objectX项,它们都有不同的名称。有其他方法吗?
{
"FormatVersion" : "2010-09-09",
"Description" : "My JSON Description",
"Parameters" : {
"Product" : {
"Description" : "Product name",
"Type" : "String",
"Default" : "cs42"
},
"DifferentObjectSize" : {
"Description" : "DifferentObjectSize",
"Type" : "String",
"Default" : "large"
},
"ObjectSize" : {
"Description" : "Worker size",
"Type" : "String",
"Default" : "medium"
}
},
"Resources" : {
"differentobject" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "DifferentObjectSize" }
}
},
"object1" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
"object2" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
"object3" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
"object4" : {
"Type" : "MyType",
"Properties" : {
"InstanceType" : { "Ref" : "ObjectSize" }
}
},
}
}
如果您想使用Json.Net,您可以将输入字符串解析为以下
JObject myObj = (JObject)JsonConvert.DeserializeObject(jsonString);
foreach(var resource in myObj["Resources"])
{
var props = resource.Children<JObject>().First();
Console.WriteLine(props["Type"] + " " + props["Properties"]["InstanceType"]["Ref"]);
}