Convert JSON to C# object -


i have json file need convert c# object, written sql database. json in format:

{     "ak": {         "anchorage": [{             "name": "john doe",             "address": "123 main st.",             "city": "anchorage",             "state": "ak",             "zip": "12345"         }],         "fairbanks": [{             "name": "sally smith",             "address": "987 main st.",             "city": "fairbanks",             "state": "ak",             "zip": "98765"         }]     } } 

i have c# class looks this:

public class location {     public string name { get; set; }     public string address { get; set; }     public string city { get; set; }     public string state { get; set; }     public int zip { get; set; } }  public class locations {     public list<location> location { get; set; } } 

i'm using newtonsoft json library. i'm not sure how can grab inner values (name, address, city, state, zip) when outer values "ak", "anchorage", "fairbanks" not have common names?

using newtonsoft:

location location = jsonconvert.deserializeobject<location>(json); 

where classes this:

public class location {     public ilist<address> addresses { get; set; } }  public class address {     public string addressname { get; set; }     [jsonproperty("name")] # you'll need attributes if dataset has name of object's property.     public string personname { get; set; }     public string address { get; set; }     public string city { get; set; }     public string state { get; set; }     public string zip { get; set; } } 

example modified here.

quick update, re-read question , saw you're having difficulty iterating on object too. missed first time round, here go:

var locations = new list<location>(); dynamic deserialisedjson = jsonconvert.deserializeobject(json);  // e.g., json => list ( "ak": { ... }, ... ) // we're iterating items of "list", e.g., "ak": { ... }, etc. foreach (var state in deserialisedjson) {     // e.g., "ak": { ... } => list ( anchorage: [{ ... }], fairbanks: [{ ... }] )     // we're iterating items of each item, e.g., anchorage: [{ ... }], etc.     foreach (var addresses in state)     {         // e.g., anchorage: [{ ... }, { ... }] => list ( { ... }, { ... } )         // because anchorage, etc., arrays, have iterate contents too, each address object within them (represented { ... } above:         foreach (var address in addresses) {             location location = jsonconvert.deserializeobject<location>(address);             // stuff location, e.g.,             locations.add(location);         }     } } 

Comments