使用JSON.net lib解析json数据

时间:2012-06-26 16:59:07

标签: c# json linq json.net

如何使用JSON.net lib解析以下json数据

    Root: {
  "data": [
    {
      "name": "query1",
      "fql_result_set": [
        {
          "thread_id": "1920370693067",
          "updated_time": 1340656102,
          "subject": "",
          "snippet": "Test",
          "snippet_author": 100002153560476
        }
      ]
    },
    {
      "name": "query2",
      "fql_result_set": [
        {
          "uid": 100002153560476,
          "name": "Santosh Singh"
        }
      ]
    }
  ]
}
    Type: Property

我尝试了以下代码,但无法获取数据

JObject j = JObject.Parse(jsonResult);
JArray data = (JArray)j["data"];

if (data != null)
        {
            foreach (var item in data[1]["fql_result_set"].Values())
            {

                string innerText = item["name"].ToString();

                string str2 = item["uid"].ToString();
                dictionary[str2] = innerText;
            }
            foreach (var item in data[0]["fql_result_set"].Values().AsJEnumerable())
            {
                FacebookMessage message;
                message.threadId = item["thread_id"].ToString();
                message.updatedTime = item["updated_time"].ToString();
                message.subject = item["subject"].ToString();
                message.snippet = item["snippet"].ToString();
                message.snippetAuthorId = item["snippet_author"].ToString();
                message.snippetAuthorName = dictionary[message.snippetAuthorId];
                allMessages.Add(message);
            }
}

1 个答案:

答案 0 :(得分:2)

首先,你的json字符串不完整。我试图将其转换为有效的:

{
    "Root": {
        "data": [
            {
                "name": "query1",
                "fql_result_set": [
                    {
                        "thread_id": "1920370693067",
                        "updated_time": 1340656102,
                        "subject": "",
                        "snippet": "Test",
                        "snippet_author": 100002153560476
                    }
                ]
            },
            {
                "name": "query2",
                "fql_result_set": [
                    {
                        "uid": 100002153560476,
                        "name": "Santosh Singh"
                    }
                ]
            }
        ]
    }
}

enter image description here

解析为:

dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach(var data in dynObj.Root.data)
{
    Console.WriteLine("{0}",data.name);
    foreach(var fql in data.fql_result_set)
    {
        foreach (JProperty keyValue in fql)
        {
            Console.WriteLine("\t{0} : {1}", keyValue.Name,keyValue.Value);
        }
    }
}