c# - Json.NET Deserializing Root and Subschema Data -
this question has answer here:
i'm new json , i'm retrieving following structure api call...
{ "customers":[ { "code":"11111", "alpha":"a", "name":"test a", "address":{ "contact":"john doe", "address1":"po box 111", "address2":"", "address3":"", "city":"de pere", "postcode":"54115", "state":"wi", "country":"usa" } }, { "code":"22222", "alpha":"b", "name":"test b", "address":{ "contact":"jane doe", "address1":"po box 222", "address2":"", "address3":"", "city":"de pere", "postcode":"54115", "state":"wi", "country":"usa" } } ] }
i'm able parse 'customers' data following...
public class customer { public string code { get; set; } public string name { get; set; } } public class customerlist { public list<customer> customers { get; set; } } dynamic jobj = jsonconvert.deserializeobject(json); dynamic jsonobj = jsonconvert.deserializeobject<customerlist>(json); foreach (var obj in jsonobj.customers) { string name = obj.name; string code = obj.code; }
but i'm having heck of time getting 'address' data. tried few things saw in other posts, no avail. appreciated.
thanks
you need create class represent address data, , add address
property existing customer
class.
public class address { public string contact { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string address3 { get; set; } public string city { get; set; } public string postcode { get; set; } public string state { get; set; } public string country { get; set; } } public class customer { ... public address address { get; set; } }
then should work fine:
var customerlist = jsonconvert.deserializeobject<customerlist>(json); foreach (var obj in customerlist.customers) { string name = obj.name; string code = obj.code; string contact = obj.address.contact; string city = obj.address.city; // etc. }
fiddle: https://dotnetfiddle.net/giudjs
Comments
Post a Comment