Extracting data from complex JSON structure in C #

I have JSON data that looks like this:

{ "position":[ { "top":[ 42, 12 ] }, { "middle":[ 10, 15 ] }, { "bottom":[ 5, 201 ] }, { "axis":[ { "X":[ 901, 51, 67 ] }, { "Y":[ 1474186, 561647 ] }, { "Z":[ 911, 1296501 ] }, 15, 20 ] } ], "validated":true, "metadata":{ "uri":"/data/complex/", "session":[ 1818, 14 ], "private":false }, "vists":0, "ok":true, "data":{ "10":{ "title":"Alpha", "author":"Justin X. Ample", "cover":"/f48hf58.tiff" }, "901":{ "title":"Tau", "author":"Felina Blank", "cover":"/45trthrref.tiff" } }, "live":null } 

From this data, I want to display the list as follows:

 Alpha, Justin X. Ample Tau, Felina Blank 

Note that keys (in my example, 10 and 901) are not predictable. So I want to somehow create an object that represents the data structure and iterate over it to get the title and author for each record.

With the basic JSON framework, I had success with something like this (using JSON.NET):

 public class Foo { public int bar { get; set; } public string baz { get; set; } public string quxx { get; set; } } ... // json = {"bar": 1, "baz":"two", "quxx":"three"} var result = await JsonConvert.DeserializeObjectAsync<Foo>(json); return result.baz // "two" 

But I can’t understand what I need to do to make it work with a complex structure.

+4
source share
2 answers
 var jObj = JsonConvert.DeserializeObject(json) as JObject; var result = jObj["data"].Children() .Cast<JProperty>() .Select(x => new { Title = (string)x.Value["title"] , Author = (string)x.Value["author"], }) .ToList(); 
+6
source

You can use it the same way as before. You just need to change the entity class to something like this:

 public class MyVeryVeryUsefulObject { public Position[] position { get; set; } public string baz { get; set; } public string quxx { get; set; } } public class Position { public Int32[] top; public Int32[] middle; public Int32[] bottom; } 

And so on. You just need to represent JSON objects as object classes in your code.

I found a useful link a while ago, maybe this will reduce your load from implementing this json structure. http://json2csharp.com/

+1
source

All Articles