Dave Dave - 1 year ago 72
JSON Question

Why is my JSON parsing null when api returns value?

I am trying to get the longitude and latitude for a postcode using the http://api.postcodes.io/postcodes/ JSON response.

If I browse to that api + a UK postcode, it returns a JSON string. However, when I try to do this and parse it programmatically with JSON.NET C# I am getting a null and I am not sure why as it seems I followed the suggestions I have seen elsewhere on this site.

This is my code

string pCode = "postcode" //user entered value
string longitude;
string latitude;

using (WebClient wc = new WebClient())
var json = wc.DownloadString("http://api.postcodes.io/postcodes/" +pCode);

dynamic data = JObject.Parse(json);

longitude = data.longitude;
latitude = data.latitude;

But longitude and latitude are returning null.

Answer Source

Judging from service response, that info is wrapped in result object:


To get values try something like:

longitude = data.result.longitude;
latitude = data.result.latitude;