Destroy dynamically called JSON objects in C # (using JSON.Net or otherwise)

I have the following JSON:

{ "aaaa": { "name": "General Name", "product": "book", "host": "book.example.com", "chapters": { "bbbb": { "name": "Chapter 1", "page": "1", "end_page": "25" } }, "categories" : { "analysis":{ "Abbbb" : { "name": "B Chapter", "id" : "9001" }, "Acccc" : { "name": "C Chapter", "id" : "9001" }, "Adddd" : { "name": "D Chapter", "id" : "9001" }, "Aeeee" : { "name": "E Chapter", "id" : "9001" }, "Affff" : { "name": "F Chapter", "id" : "9001" }, "Agggg" : { "name": "G Chapter", "id" : "9001" } }, "sources":{ "acks" : { "name": "S. Spielberg", "id" : "9001" } } } } "yyyy": { "name": "Y General Name", "product": "Y book", "host": "ybook.example.com", ... } "zzzz": { "name": "Z General Name", "product": "Z book", "host": "zbook.example.com", ... } 

The values ​​for aaaa , yyyy and zzzz can be any string, and there can be any number.

I need to extract all the values ​​of [aaaa|yyyy|zzz].categories.analysis . That is, I need to specify Dictionary<string, string> the object name (for example, Abbbb , Acccc , etc.) and the identifier, ignoring the name string.

eg., [Abbbb, 9001] [Acccc, 9001] [Adddd, 9001] ... [Zaaaa, 9001]

I have been too long and feel that I am missing something obvious. I tried JSON.net and my own serialization. This is a trivial task in all other languages ​​that I used.

I came close to something like this:

 var ajsonObject = JsonConvert.DeserializeObject<dynamic>(jsonString); var oasearch_categories = ajsonObject.aaaa.categories.analysis; 

But then again, aaaa can be any string, so I'm not sure how to dynamically refer.

+6
source share
1 answer

Took the time, but I figured it out. My requirement has changed a bit from the original question ... My final result was needed for the List Dictionary, so I would get a dictionary like:

 DICT[ {"9001", ["Abbbb", "Acccc", "Adddd", ...]}, {"9002", ["Zbbbb, Zdddd", ...]}, etc. ] | key | | value | | key | | value | 

This is the result:

 Dictionary<string, List<string>> idsAndTheirNames = new Dictionary<string, List<string>>(); try { var ajsonObject = JsonConvert.DeserializeObject<dynamic>(JSONstring); foreach (var child in ajsonObject.Children()) { foreach (var product in child.Children()) { var categories = product.categories.analysis; foreach (var category in categories.Children()) { foreach (var subcat in category) { List<string> name = idsAndTheirNames[(string)subcat.id]; //eg, "9001" if (name == null) name = new List<string>(); name.Add(category.Name); //eg, "Abbbb" idsAndTheirNames[(string)subcat.id] = name; //"9001" -> ["Abbbb", "Acccc", etc.] System.Diagnostics.Debug.WriteLine((string)category.Name); //"Abbbb" System.Diagnostics.Debug.WriteLine((string)subcat.name); //"Chapter B" System.Diagnostics.Debug.WriteLine((string)subcat.id); //"9001" } } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("JSON ERROR: " + ex.Message); } 
+2
source

All Articles