Search code examples
c#jsonapihttpwebrequest

Deserializing json C#


I have code that returns json data from a post api call. The data is in the below format:

{"data":[{"name":"123","pwd":123},{"name":"456","pwd":456},{"name":"789","pwd":789}]",duration":5309,"query":"myquery","timeout":300}

To deserialise the above json, I have written the following code:

Product myprod = JsonConvert.DeserializeObject<Product>(result);
var results = myprod.result;

My data remains null with count=0. Could anyone help me with where am I going wrong ?


Solution

  • First your json is invalid. Here is the same one but with fixes.

    {"data":[{"name":"123","pwd":123},{"name":"456","pwd":456},{"name":"789","pwd":789}],"duration":5309,"query":"myquery","timeout":300}
    

    And with this json model should look like this:

    public class Rootobject
    {
        public Datum[] data { get; set; }
        public int duration { get; set; }
        public string query { get; set; }
        public int timeout { get; set; }
    }
    
    public class Datum
    {
        public string name { get; set; }
        public int pwd { get; set; }
    }