Search code examples
c#.netjsonjavascriptserializer

How can I deserialize JSON to a simple Dictionary<string,object> to datagridview using only dynamics?


I have a simple key/value list in JSON from a webserver and need to put this data in a datagridview without any dll as JSON.Net. I found Count equals a three (array json) but I can´t extract it. Example:

        var json = new WebClient().DownloadString("https://server.com/getMsg.aspx");
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var dictObj = serializer.Deserialize<Dictionary<string, dynamic>>(json);
        List<Person> list = new List<Person>();
        for (int i = 0; i < dictObj["result"].Count; i++)
        {
            Person p = new Person();
            p.Id = dictObj["result"].Value[i].id;
            p.Name = dictObj["result"].Value[i].name;
            p.Age = dictObj["result"].Value[i].age; 
            list.Add(p);
        }

        datagridView1.DataSource = list;

The downloaded json is presented below:

{"result": [                                                                
    {"id": "14", "name": "sdfsdfsdf", "age": "40" },
    {"id": "13", "name": "vfdgdg", "age": "50" },
    {"id": "12", "name": "grgetge","age": "60" } ] }

Solution

  • I would try to create a class RootObject to carry your Person collection instance.

    then use serializer.Deserialize<RootObject> to make it.

    public class Person
    {
        public string id { get; set; }
        public string name { get; set; }
        public string age { get; set; }
    }
    
    public class RootObject
    {
        public List<Person> result { get; set; }
    }
    

    Then you can use List<Person> instead of for loop directly

    var dictObj = serializer.Deserialize<RootObject>(json);
    datagridView1.DataSource = dictObj.result;
    

    Note

    I would suggest you use Json.net third-party library instead of JavaScriptSerializer because its performance will be better than JavaScriptSerializer

    And it use very simple, use JsonConvert.DeserializeObject<T>() can Deserialize json to object.

    var dictObj = JsonConvert.DeserializeObject<RootObject>(Json);
    datagridView1.DataSource = dictObj.result;