Destroy nested JSON in C # objects

I get JSON back from the API, which looks like this:

{ "Items": { "Item322A": [{ "prop1": "string", "prop2": "string", "prop3": 1, "prop4": false },{ "prop1": "string", "prop2": "string", "prop3": 0, "prop4": false }], "Item2B": [{ "prop1": "string", "prop2": "string", "prop3": 14, "prop4": true }] }, "Errors": ["String"] } 

I tried several approaches for representing this JSON in C # objects (too many to list here). I tried with lists and dictionaries, here is a recent example of how I tried to present it:

  private class Response { public Item Items { get; set; } public string[] Errors { get; set; } } private class Item { public List<SubItem> SubItems { get; set; } } private class SubItem { public List<Info> Infos { get; set; } } private class Info { public string Prop1 { get; set; } public string Prop2 { get; set; } public int Prop3 { get; set; } public bool Prop4 { get; set; } } 

And here is the method I use to deserialize JSON:

  using (var sr = new StringReader(responseJSON)) using (var jr = new JsonTextReader(sr)) { var serial = new JsonSerializer(); serial.Formatting = Formatting.Indented; var obj = serial.Deserialize<Response>(jr); } 

obj contains Items and Errors . And Items contains SubItems , but SubItems is null . Thus, nothing but Errors is actually deserialized.

It should be simple, but for some reason I cannot understand the correct representation of the object

+6
source share
2 answers

For "Items" use Dictionary<string, List<Info>> , i.e.:

 class Response { public Dictionary<string, List<Info>> Items { get; set; } public string[] Errors { get; set; } } class Info { public string Prop1 { get; set; } public string Prop2 { get; set; } public int Prop3 { get; set; } public bool Prop4 { get; set; } } 

It is assumed that the names of the item "Item322A" and "Item2B" will vary from answer to answer and will read these names in the form of dictionary keys.

EXAMPLE fiddle .

+8
source

Use this site to submit:

http://json2csharp.com/

something like this might help you

 public class Item322A { public string prop1 { get; set; } public string prop2 { get; set; } public int prop3 { get; set; } public bool prop4 { get; set; } } public class Item2B { public string prop1 { get; set; } public string prop2 { get; set; } public int prop3 { get; set; } public bool prop4 { get; set; } } public class Items { public List<Item322A> Item322A { get; set; } public List<Item2B> Item2B { get; set; } } public class jsonObject { public Items Items { get; set; } public List<string> Errors { get; set; } } 

Here's how to deserialize (use the JsonConvert class):

 jsonObject ourlisting = JsonConvert.DeserializeObject<jsonObject>(strJSON); 
+10
source

All Articles