2012-01-16 92 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"]); 
}