Question

I've been trying to de-serialize a JSON stream in C# using JSON.Net

I have a JObject 'JO1' and when I do a JO1.ToString() on that the string contents are:

{
  "Successful": true,
  "Value": [
    {
      "no": "1",
      "name": "Accounting"
    },
    {
      "no": "2",
      "name": "Marketing"
    },
    {
      "no": "3",
      "name": "Information Technology"
    }
  ]
}

I have tried the following .NET code to no avail.

public class main()
{
  public void main()
  {
   JObject jo = new JObject();
   jo = functionthatretrievestheJSONdata();

   List<departments> dt1 = JsonConvert.DeserializeObject<List<departments>>(jo.ToString());
  }
}

public class departments
{
    public int no { get; set; }
    public string name { get; set; }
}

Can someone please give me a pointer in the right direction?

Was it helpful?

Solution

You're going to need a class to wrap List<departments>, like this:

public class DeserializedDepartments
{
    public bool Successful { get; set; }
    public List<departments> Value { get; set; }
}

and so you'd deserialize like this:

DeserializedDepartments dt1 =
    JsonConvert.DeserializeObject<DeserializedDepartments>(jo.ToString());

Now your List<departments> is in the Value of dt1; or dt1.Value.

OTHER TIPS

You are not taking into account that the list is an array attached to another object.

you have an object with a boolean value called Successful and an array of Departments called Value.

Try this:

public class main()
{
    public void main()
    {
        JObject jo = new JObject();
        jo = functionthatretrievestheJSONdata();

        Results dt1 = JsonConvert.DeserializeObject<Results>(jo.ToString());
        var depts = dt1.Value;
    }
}

public class Results 
{
    public bool Successful {get;set;}
    public List<Department> Value {get;set;}
}

public class Department
{
    public int no { get; set; }
    public string name { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top