How to Deserialize JSON data?

eitan barazani picture eitan barazani · Aug 14, 2013 · Viewed 101.8k times · Source

I am new to working with JSON data.

I am reading data from a web service. The query data sent back is the following:

[["B02001_001E","NAME","state"],
 ["4712651","Alabama","01"],
 ["691189","Alaska","02"],
 ["6246816","Arizona","04"],
 ["18511620","Florida","12"],
 ["9468815","Georgia","13"],
 ["1333591","Hawaii","15"],
 ["1526797","Idaho","16"],
 ["3762322","Puerto Rico","72"]]

Is there a way to Deserialize this data in such a way that the base object will be generated without me first defining what the object is like? In the above example the object is defined by the first row:

           ["B02001_001E","NAME","state"],

In general the web service will return the query data formatted as a two dimensional JSON array where the first row provides column names and subsequent rows provide data values.

Answer

evanmcdonnal picture evanmcdonnal · Aug 14, 2013

You can deserialize this really easily. The data's structure in C# is just List<string[]> so you could just do;

  List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);

The above code is assuming you're using json.NET.

EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]> for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][] but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.