2012-09-20 81 views
4

我有一個JSON這樣JSON解析C#

{ "nodes" : [{"id" : "36018","title" : "Fotarı","date" : "20.09.2012 00:45", "short_description" : "Dünrina, rr!","bigimage_width" : "468","bigimage" : "https://qew","croppedimage" : "https://qwe.jpg"},{"id" : "36009","title" : "ey","date" : "20.09.2012 00:03", "short_description" : "İntız!","bigimage_width" : "220","bigimage" : "https://312.jpg","croppedimage" : "https://41172.jpg"},{"id" : "35915","title" : "ai!","date" : "20.09.2012 00:02", "short_description" : "Ssdi...","bigimage_width" : "220","bigimage" : "https://qwe.qwe" : "https://asd.asd"},... 

所以我這樣做

JObject j = JObject.Parse(x); // x is downloaded JSon code 
JArray sonuc = (JArray)j["nodes"]; 

但現在我有

[{"id":"1","name":"news"},{"id":"2","name":"hardware"},{"id":"3","name":"software"},{"id":"4","name":"\internet"},{"id":"6","name":"tv!"},{"id":"7","name":"texts"},{"id":"8","name":"update"},... 

所以我應該怎麼做我的代碼讓它起作用?

JObject j = JObject.Parse(x); // gives JsonReaderException exception here 
JArray sonuc = (JArray)j[""]; 

回答

7

如果在JSON數組(注意開[]括號內),您可以直接與JArray.Parse靜態方法解析它:

JArray sonuc = JArray.Parse(x); 
+0

它的工作謝謝! –

-1
JArray sonuc = JArray(x); 

應該完成工作爲你..因爲x已經在數組的形式

+1

你的示例沒有編譯你缺少'new',並且沒有'JArray'的構造函數,它在JSON.Net中使用'string' ...'JArray.Parse'用於解析字符串。 – nemesv

1

你有很多方法來解析你的JSON,例如,你可以使用dynamic

dynamic obj1 = JsonConvert.DeserializeObject(json); 
foreach (var node in obj1.nodes) 
{ 
    Console.WriteLine("{0} {1}", node.id, node.title); 
} 

或LINQ

var obj2 = (JObject)JsonConvert.DeserializeObject(json); 
var nodes= obj2["nodes"].Children() 
      .Select(node => new 
      { 
       Id= (string)node["id"], 
       Title = (string)node["title"] 
      }) 
      .ToList(); 
+0

我不明白deserializeObject的作用。 jsonArray temp.name =(string)sonuc [i] [「name」]; temp.id = Int32.Parse((string)sonuc [i] [「id」]); //在for循環中 –