1

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.

4
  • What does "doesn't work" mean?
    – Sayse
    Commented Mar 13, 2014 at 19:05
  • please don't create a class called Object for your own safety Commented Mar 13, 2014 at 19:07
  • Do any of the Related answers over there help? ---------> Seems like fairly relevant stuff Commented Mar 13, 2014 at 19:09
  • @Sayse the OP should be more specific, but in this case it's pretty obvious. It doesn't compile because he's trying to iterate over an instance of object
    – dcastro
    Commented Mar 13, 2014 at 19:11

3 Answers 3

2

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
}
1

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.

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.