2012-01-16 94 views
0

我有我想解析到C#中的以下JSON。我试图避免外部图书馆,但如果我必须我可以使用它们。现在,我正在使用JavaScriptSerializer从JSON文件解析另一个stackoverflow question上的答案。不幸的是,我可以在Resources下有任意数量的objectX项目,并且它们都有不同的名称。有没有另外一种方法呢?解析JSON文件C#

{ 
    "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" } 
      } 
     }, 

    } 
} 
+0

你瞄准什么版本的.NET? – Kane 2012-01-16 22:15:41

+0

我们正在使用.net 4.0 – 2012-01-16 22:28:44

+0

那么,我推出了自己的。 JSON并不是非常复杂,你可以在一天左右完成。 – 2012-01-16 22:17:25

回答

4

如果你想使用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"]); 
}