-1

I'm quite new to JSON with C# (Using VS2017). Tried accessing each element of this object via code (e.g. Getting the strings "Obj1", "Obj2", "Obj3" and then the values of each of their members (Id and name).

I do not know in advance how many "ObjX" there will be or their names. I'm trying to load this list into some class and then convert it into a CSV (or SQL inserts).

Tried with JSON.net and JsonFx but I think my skills are just not strong enough to understand how to do this other than brute-force string manipulation functions. Can anyone help?

{  
"OBJ1":{  
      "id":1,
      "name":"Name1",
},
"OBJ2":{  
      "id":2,
      "name":"Name2",
},
"OBJ3":{  
      "id":3,
      "name":"Name3",
}
}
Nicksta
  • 43
  • 1
  • 5
  • 1
    Possible duplicate of [How can I parse JSON with C#?](https://stackoverflow.com/q/6620165/11683) – GSerg Jul 01 '17 at 06:29
  • 1
    Possible duplicate of [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/q/3142495/11683) – GSerg Jul 01 '17 at 06:29

1 Answers1

2

Create a class, MyClass with two properties, int Id and string Name.

public class MyClass
{
    public int Id {get; set;}
    public string Name {get;set;}
}

Then, depending on how you want to do it you can either deserilize it to a Dictionary or create a MyClassRoot object with three MyClass properties.

I recommend the Dictionary approach. If you use the Dictionary approach your code will still work if more properties gets added to the JSON. If you use the MyClassRoot solution you will need to add the corresponding property to the MyClassRoot if the json updates.

Then with JSON.Net you can deserialize the object like this.

var result = JsonConvert.DeserializeObject<Dictionary<string, MyClass>>(json);

The "OBJ1", "OBJ2" and so on will then be keys in the dictionary and you can access the values like this:

var obj1 = result["OBJ1"];
var obj1Name = obj1.Name;
var obj1Id = obj1.Id;

To get all the MyClass objects to a list, simply do the following:

var list = result.ToList();

MyClassRoot approach(not recommended at all, just a POC):

public class MyClassRoot
{
    public MyClass Obj1 {get;set;}
    public MyClass Obj2{get;set;}
    public MyClass Obj3{get;set;}
}

var result = JsonConvert.DeserializeObject<MyClassRoot>(json);
var obj1Name = result.Obj1.Name;
var obj1Id = result.Obj1.Id;
JOSEFtw
  • 9,781
  • 9
  • 49
  • 67
  • Ok - I need to provide some more details, 1st approach is more valid. There could be infinite ObjN in the response and I'd like to load them into a list. – Nicksta Jul 01 '17 at 06:55
  • Moreover - I don't know the names of "Obj1", "Obj2" in advance, they could be new values which I haven't seen yet. What I'm trying to build is something that converts this json into a CSV, with code (I know there are online converters but that's not my goal) – Nicksta Jul 01 '17 at 06:57
  • You guys are amazing - THANKS! – Nicksta Jul 01 '17 at 07:04