C#中的Json解析

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[""];
2个回答

7

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

JArray sonuc = JArray.Parse(x);

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();

我不理解deserializeObject的作用。在将JSON转换为JsonArray之后,我使用它。temp.name = (string)sonuc[i]["name"]; temp.id = Int32.Parse((string)sonuc[i]["id]");//在for循环中。 - E.Mert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接