【问题标题】:How to find JSON array present in JSON object or not android如何找到JSON对象中存在的JSON数组或不存在android
【发布时间】:2015-02-07 09:02:53
【问题描述】:

我正在使用 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 数组。 如果在场,我将使用我的代码。否则我只会向用户显示警告消息。

【问题讨论】:

  • 可以查看路由数组的长度

标签: java android arrays json


【解决方案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
    }

【讨论】:

  • 嘿如何从这段代码中获取状态元素? {“路线”:[],“状态”:“NOT_FOUND”}
【解决方案2】:

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

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

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

例子

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 2013-09-29
    • 2014-05-13
    相关资源
    最近更新 更多