如何检查json数据是否存在?

时间:2014-02-15 12:58:01

标签: c# json windows-phone-8 json.net

我通过json生成一个http请求获取结果。如果有结果,一切正常,但如果没有结果,则在尝试将值显示到文本块时崩溃。我试试这个,但它不起作用

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();
}

以下是json数据的结构:

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; }
}

2 个答案:

答案 0 :(得分:2)

您正在检查apiData.search_api.result [0]是否为null,但在尝试检查嵌套元素之前,您需要首先检查整个apiData对象是否为null。

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

答案 1 :(得分:1)

在访问其属性之前,始终先检查变量是否为空,并且在使用索引器访问其元素之前,始终先检查List<T>是否有任何元素。

在这种情况下,您需要检查apiDataapiData.search_apiapiData.search_api.result是否为空以及apiData.search_api.resultapiData.search_api.result[0].areaName是否包含任何元素。

尝试更改此

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

到这个

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();
}