如何找到JSON对象中存在的JSON数组或不是android

时间:2015-02-07 09:02:54

标签: java android arrays json

我正在使用JSON对象。它给出了这样的结果

{
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 19.0759817,
               "lng" : 80.27071789999999
            },
            "southwest" : {
               "lat" : 12.5100381,
               "lng" : 72.8772599
            }
         },
         "copyrights" : "Map data ©2015 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "1,334 km",
                  "value" : 1333618
               },
               "duration" : {
                  "text" : "17 hours 43 mins",
                  "value" : 63763
               },
               "end_address" : "Mumbai, Maharashtra, India",
               "end_location" : {
                  "lat" : 19.0759817,
                  "lng" : 72.8776544
               },
               "start_address" : "Chennai, Tamil Nadu, India",
               "start_location" : {
                  "lat" : 13.0826782,
                  "lng" : 80.27071789999999
               },

所以我正在检索以下数组routes - > legs -> distance`。使用以下代码

        JSONArray one = reader.getJSONArray("routes");
              for ( i = 0; i < one.length(); i++) {

                 two = one.getJSONObject(i);

                 three = two.getJSONArray("legs");

                for ( j = 0; j < three.length(); j++) {

                   four = three.getJSONObject(j);
                   bounds = four.getJSONObject("distance");

                    distance[i]=bounds.getString("text");

它工作正常。有时候输入错误时我的JSON结果就像这样。

{
   "routes" : [],
   "status" : "NOT_FOUND"
}

所以当我在这个空的JSON对象中搜索腿时,我的android应用程序会自动挂起并终止。所以我应该检查我的JSON对象中是否存在legs数组。 如果存在,我将使用我的代码。否则我只会向用户显示警告信息。

2 个答案:

答案 0 :(得分:1)

你可以查看长度或路由数组,如果有数据,你可以做你的东西:

JSONArray one = reader.getJSONArray("routes");
      if(one.size()>0)
    {
          for ( i = 0; i < one.length(); i++) {

             two = one.getJSONObject(i);

             three = two.getJSONArray("legs");

            for ( j = 0; j < three.length(); j++) {

               four = three.getJSONObject(j);
               bounds = four.getJSONObject("distance");

                distance[i]=bounds.getString("text");
 }}
else
 {//handle empty json array here
    }

答案 1 :(得分:1)

JSONObject类有一个名为“has”的方法

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

如果此对象具有name的映射,则返回true。映射可能为NULL。

例如

if (jsonObject.has("yourkey"))
    {
        // it will return true;
    }
    else
    {
        //it will return false;
    }