JSON Deserializer returning NULL Values

  • A+

I am trying to consume a REST API via a C# Console Application and I've got as far as getting the webservice to return the JSON file, with the format:

{"status":200,"result":{"postcode":"SW1W0DT","quality":1,"eastings":528813,"northings":178953,"country":"England","nhs_ha":"London","longitude":-0.145828,"latitude":51.494853,"european_electoral_region":"London","primary_care_trust":"Westminster","region":"London","lsoa":"Westminster 023E","msoa":"Westminster 023","incode":"0DT","outcode":"SW1W","parliamentary_constituency":"Cities of London and Westminster","admin_district":"Westminster","parish":"Westminster, unparished area","admin_county":null,"admin_ward":"Warwick","ccg":"NHS Central London (Westminster)","nuts":"Westminster","codes":{"admin_district":"E09000033","admin_county":"E99999999","admin_ward":"E05000647","parish":"E43000236","parliamentary_constituency":"E14000639","ccg":"E38000031","nuts":"UKI32"}}} 

I have created a class AddressInfo which is as follows:

public class AddressInfo {     public string postcode { get; set; }     public int quality { get; set; }     public int eastings { get; set; }     public int northings { get; set; }     public string country { get; set; }     public string nhs_ha { get; set; }     public string admin_county { get; set; }     public string admin_district { get; set; }     public string admin_ward { get; set; }     public double longitude { get; set; }     public double latitude { get; set; }     public string parliamentary_constituency { get; set; }     public string european_electoral_region { get; set; }     public string primary_care_trust { get; set; }     public string region { get; set; }     public string parish { get; set; }     public string lsoa { get; set; }     public string msoa { get; set; }     public string ccg { get; set; }     public string nuts { get; set; }     public object codes { get; set; }  } 

The code to call the API and get the values is:

string strJSON = string.Empty;  strJSON = rClient.makeRequest(); Console.Write(strJSON);  AddressInfo AI = new AddressInfo(); AI = Newtonsoft.Json.JsonConvert.DeserializeObject<AddressInfo>(strJSON); 

However, when I debug, AI is returning the values as "NULL".



Notice that your JSON has a nested structure. The AddressInfo is contained within its result property, it isn't at the top level.

Your actual class structure to deserialize the entire JSON response should look something like this (I've called the class JsonResponse but you can name it whatever you want):

class JsonResponse{     public int status { get; set; }     public AddressInfo result { get; set; } } 

Then deserialize it like this:

JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJSON); AddressInfo addressInfo = res.result; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: