Junaid Bilal
Junaid Bilal

Reputation: 35

extract data from JSON to datagridview winforms c#

I'm trying to extract data from JSON but i searched and tried many examples but nothing worked for me. I just want messages node and extract its data to datagridview. Json Object looks like:

{
"limit" : "10",
"offset" : "0",
"size" : "10",
"messages": [{
 "address": "+12111",
"body": "hello",
"_id": "4113",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "78454",
"body": "my data",
"_id": "4103",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "7421",
"body": "yes",
"_id": "4101",
"msg_box": "outbox",
"sim_slot": "0"
},
{
"address": "+1235454878",
"body": "balance",
"_id": "4099",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "+123545",
"body": "hello",
"_id": "4098",
"msg_box": "inbox",
"sim_slot": "0"
}
]
}

Upvotes: 1

Views: 3287

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29252

If you have JSON but don't know how to create corresponding classes that deserialize the JSON into objects, json2csharp.com is helpful. You paste in the JSON and it does its best to infer C# classes from it. You might decide to tweak the classes a little as needed but it gives you a good starting point. Given your JSON it outputs this:

public class Message
{
    public string address { get; set; }
    public string body { get; set; }
    public string _id { get; set; }
    public string msg_box { get; set; }
    public string sim_slot { get; set; }
}

public class RootObject
{
    public string limit { get; set; }
    public string offset { get; set; }
    public string size { get; set; }
    public List<Message> messages { get; set; }
}

Now using Newtonsoft.Json you can do this:

var myObject = JsonConvert.DeserializeObject<RootObject>(stringContainingJson);

A property named _id is a little clunky, so you can change the name and use an attribute to map the the property to the JSON element, like this:

[JsonProperty("_id")]
public string Id { get; set; }

Now you can bind the list of Message to your DataGridView.

myDataGridView.DataSource = myObject.messages;

Upvotes: 2

Related Questions