我有以下要解析成C#的JSON。我尽量避免使用外部库,但如果有必要,我可以使用它们。现在,我正在使用JavaScriptSerializer方法从一个JSON文件中解析出另一个stackoverflow question上的答案。不幸的是,我可以在参考资料下使用任意数量的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" }
}
},
}
}发布于 2012-01-17 06:28:26
如果您考虑使用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"]);
}https://stackoverflow.com/questions/8887029
复制相似问题