使用Json.net和C#反序列化嵌套的json字符串?

时间:2013-04-29 04:28:27

标签: c# json json.net

我的字符串json

{"data":[{"id":"CAMVqgY1g1cdLU5anDL69Tt5pyRh51-qkyKMHWHgH2mAG+vn+xQ%40mail.gmail.com","content":"Coba ngirim email mohon diterima\r\n","judul":"coba 1","sender":"\"Aldo Erianda\""},{"id":"CAMVqgY1Trb5ZShRxzoX%3D0xaVQs5-Psh0J8V3JwQYVevcr8i5WA%40mail.gmail.com","content":"sampai nga ya\r\n","judul":"coba 2","sender":"\"Aldo Erianda\""}]}

我想在“数据”中计算记录,并在控制台或richtextbox中显示记录。 几个教程仍然让我很难理解。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

这适用于您的具体情况。它不适用于任何json字符串。

var json = "{\"data\":[{\"id\":\"CAMVqgY1g1cdLU5anDL69Tt5pyRh51-qkyKMHWHgH2mAG+vn+xQ%40mail.gmail.com\",\"content\":\"Coba ngirim email mohon diterima\r\n\",\"judul\":\"coba 1\",\"sender\":\"Aldo Erianda\"},{\"id\":\"CAMVqgY1Trb5ZShRxzoX%3D0xaVQs5-Psh0J8V3JwQYVevcr8i5WA%40mail.gmail.com\",\"content\":\"sampai nga ya\r\n\",\"judul\":\"coba 2\",\"sender\":\"Aldo Erianda\"}]}";
var deserialized = JsonConvert.DeserializeObject<IDictionary<string, JArray>>(json);
JArray recordList = deserialized["data"];
foreach (JObject record in recordList)
{
    Console.WriteLine("id: " + record["id"]);
    Console.WriteLine("content: " + record["content"]);
    Console.WriteLine("judul: " + record["judul"]);
    Console.WriteLine("sender: " + record["sender"]);
}
Console.WriteLine("count: " + recordList.Count);

注意:我通过转义所有引用来略微修改你的json,使它成为一个有效的C#字符串。此外,我认为您的发件人价值还有额外的报价。