4

我有一个像这样的Json

{ "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[""];
4

2 回答 2

7

如果您在 JSON 中有一个数组(注意左括号[和右括号),您可以使用JArray.Parse静态方法]直接解析它:

JArray sonuc = JArray.Parse(x);
于 2012-09-20T07:26:20.907 回答
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();
于 2012-09-20T07:50:52.110 回答