0

My string 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\""}]}

I want to count record inside "data", and show the records in console or richtextbox. several tutorial still make me difficult to figure out. how should I do in step by step?

1 Answers1

0

This should work for your specific case. It's not generalizable to any json string.

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

Note: I slightly modified your json by escaping all the quotations to make it a valid C# string. Also, I think you have extra quotations around the value of your sender.

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
  • it works.. just like what i expected.. anyway, do i need to make additional class like this below: class ResponseEntity { public ResponseEntity() { data = new List(); } public List data; } class data { public string id { get; set; } public string content { get; set; } public string judul { get; set; } public string sender { get; set; } } – Luthfan Pramono Apr 29 '13 at 05:15
  • Depending on what your trying to accomplish, these classes could be useful. I think the ResponseEntity class may be overkill. I'd just store the information in a List. – Steven Wexler Apr 29 '13 at 05:21
  • could you please explain this part.. **var deserialized = JsonConvert.DeserializeObject>(json);** if you don't mind. – Luthfan Pramono Apr 29 '13 at 05:21
  • The json object is serialized as a string. We want to deserialize the string so we can parse and use the values in the json object. The thing is, we need to deserialize (i.e. translate) the json string to _something_. I chose to deserialize the json string to a dictionary of string => JArray because it seemed to fit the data well. In this case the deserialization returned a dictionary of "data" => [ /* Array of records */ ]. (I chose JArray because it's Json.Net's closest representation to an array) – Steven Wexler Apr 29 '13 at 05:28