user3168511
user3168511

Reputation: 254

How to check for json data exist?

I generate a http request du get results via json. If there is a result everything works but if there is no result it crashes on trying to display the value into a textblock. I try this but it's not working

HttpClient client = new HttpClient();
string url = "http://api.worldweatheronline.com/free/v1/search.ashx?q=" + Location + "&format=json&key=xxxx";
string DatenURL = await client.GetStringAsync(url);
RootObject apiData = JsonConvert.DeserializeObject<RootObject>(DatenURL);

if (apiData.search_api.result[0] != null)
{
    txt_Result1.Text = apiData.search_api.result[0].areaName[0].value.ToString();
}

Here is the structure for json data:

public class AreaName
{
    public string value { get; set; }
}

public class Country
{
    public string value { get; set; }
}

public class Region
{
    public string value { get; set; }
}

public class WeatherUrl
{
    public string value { get; set; }
}

public class Result
{
    public List<AreaName> areaName { get; set; }
    public List<Country> country { get; set; }
    public string latitude { get; set; }
    public string longitude { get; set; }
    public string population { get; set; }
    public List<Region> region { get; set; }
    public List<WeatherUrl> weatherUrl { get; set; }
}

public class SearchApi
{
    public List<Result> result { get; set; }
}

public class RootObject
{
    public SearchApi search_api { get; set; }
}

Upvotes: 1

Views: 1221

Answers (2)

ekad
ekad

Reputation: 14614

Always check if a variable is null first before accessing its properties, and always check if a List<T> has any elements first before accessing its elements using an indexer.

In this case, you need to check if apiData, apiData.search_api, apiData.search_api.result are null and if apiData.search_api.result and apiData.search_api.result[0].areaName have any elements.

Try to change this

if (apiData.search_api.result[0] != null)
{
    txt_Result1.Text = apiData.search_api.result[0].areaName[0].value.ToString();
}

to this

if (apiData != null && apiData.search_api != null 
    && apiData.search_api.result != null && apiData.search_api.result.Count > 0
    && apiData.search_api.result[0].areaName.Count > 0)
{
    txt_Result1.Text = apiData.search_api.result[0].areaName[0].value.ToString();
}

Upvotes: 1

E.J. Brennan
E.J. Brennan

Reputation: 46859

You are checking if apiData.search_api.result[0] is null, but you need to first check to see if the entire apiData object is null before you try to check nested elements.

i.e.

if (apiData != null)
  if (apiData.search_api.result[0] != null)
  {
      txt_Result1.Text = apiData.search_api.result[0].areaName[0].value.ToString();
  }

Upvotes: 2

Related Questions