jacobz
jacobz

Reputation: 3291

Deserializing JSON into list

I got some JSON:

{
  "data": {
    "1001": {
      "name": "Test name 1"
    },
    "1004": {
      "name": "Test name 2"
    },
    "1005": {
      "name": "Test name 3"
    }
  }
}

How do I deserialize this into a list that, once deserialized, will contain 1001, 1004 and 1005?

My code so far:

public class Data
{
    public string name { get; set; }
}
public class Object
{
    public Data data { get; set; }
}

...

List<string> list = new List<string>();
var data = JsonConvert.DeserializeObject<Object>(json);

foreach (var s in data)
    list.Add(s);

This, however, doesn't work.

Upvotes: 1

Views: 106

Answers (3)

Nikhil
Nikhil

Reputation: 1151

You can't convert it directly to a list. The problem is that 1001, 1004, and 1005 are keys for your objects. A list would not contain the numbers, but the names within it. This means you'd lose some data.

What you can do is use dictionaries, and then iterate over those.

Class Data should include a Dictionary of another type, lets call it Name (so ). Name would have one member, string name.

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

Try to model your classes according to JSON structure:

public class Data
{
    public Dictionary<string, Node> data { get; set; }
}

public class Node
{
    public string name { get; set; }
}

var result = JsonConvert.DeserializeObject<Data>(json);

Then you can iterate over the items:

foreach(var item in result.data)
{
    //do stuff
}

Upvotes: 2

Chris Knight
Chris Knight

Reputation: 1476

Your model does not match your JSON. Your JSON says there is an object called 'data' that has three properties named '1001', '1004', and '1005', each of which has a property called 'name'. Your c# model should be something like this:

public class Data
{
    public Child 1001 { get; set; }
    public Child 1004 { get; set; }
    public Child 1005 { get; set; }
}
public class Child
{
    public string name{ get; set; }
}

You may want to consider using a dynamic object instead.

Upvotes: 0

Related Questions