json解析响应可以有一个或多个对象

时间:2010-10-29 13:20:24

标签: android json parsing varying

我需要使用android json解析器在android中解析这个响应,但我无法找到答案的地方是:

如果例如“itineraries”可以包含一个或有时更多类型行程的对象,我该如何解析数据? 如果它包含一个比它像这样返回但是如果它包含更多它将返回[] 在这个例子中,“itinerary”不能放入JsonArray,因为很明显它不是一个数组。 (没有放在[]右边?)

我该怎么解析这个?任何例子?

  {
   "plan":{
      "date":"2010-10-20T00:00:00+02:00",
      "from":{
         "name":"Булевар Партизански Одреди",
         "stopId":"123",
         "lon":"21.373255285035548",
         "lat":"42.00736515785779",
         "geometry":"{\"type\": \"Point\", \"coordinates\": [21.373255285035548,42.00736515785779]}"
      },
      "to":{
         "name":"Булевар Партизански Одреди",
         "stopId":"123",
         "lon":"21.37228809181389",
         "lat":"42.00762790595865",
         "geometry":"{\"type\": \"Point\", \"coordinates\": [21.37228809181389,42.00762790595865]}"
      },
      "itineraries":{
         "itinerary":{
            "duration":"159000",
            "startTime":"2010-10-20T00:00:00+02:00",
            "endTime":"2010-10-20T00:02:39+02:00",
            "walkTime":"159000",
            "transitTime":"0",
            "waitingTime":"0",
            "walkDistance":"212.6496008849819",
            "elevationLost":"0.0",
            "elevationGained":"0.0",
            "transfers":"0",
            "legs":{
               "leg":{
                  "@route":"Булевар Партизански Одреди",
                  "@mode":"WALK",
                  "startTime":"2010-10-20T00:00:00+02:00",
                  "endTime":"2010-10-20T00:02:39+02:00",
                  "distance":"212.6496008849819",
                  "from":{
                     "name":"Булевар Партизански Одреди",
                     "lon":"21.373255285035548",
                     "lat":"42.00736515785779",
                     "geometry":"{\"type\": \"Point\", \"coordinates\": [21.373255285035548,42.00736515785779]}"
                  },
                  "to":{
                     "name":"Булевар Партизански Одреди",
                     "lon":"21.37228809181389",
                     "lat":"42.00762790595865",
                     "geometry":"{\"type\": \"Point\", \"coordinates\": [21.37228809181389,42.00762790595865]}"
                  },
                  "legGeometry":{
                     "length":"3",
                     "points":"_qk_GymmaCf@qC{ArI"
                  },
                  "steps":{
                     "walkSteps":{
                        "distance":"212.6496008849819",
                        "streetName":"Булевар Партизански Одреди",
                        "absoluteDirection":"EAST",
                        "stayOn":"false",
                        "becomes":"false",
                        "lon":"21.373255285035548",
                        "lat":"42.00736515785779",
                        "elevation":""
                     }
                  },
                  "duration":"159000"
               }
            },
            "tooSloped":"false"
         }
      }
   },
   "requestParameters":{
      "entry":[
         {
            "key":"optimize",
            "value":"QUICK"
         },
         {
            "key":"time",
            "value":"9:40 am\""
         },
         {
            "key":"wheelchair",
            "value":"false"
         },
         {
            "key":"maxWalkDistance",
            "value":"800.0"
         },
         {
            "key":"fromPlace",
            "value":"42.0074711701039,21.3732840843651"
         },
         {
            "key":"toPlace",
            "value":"42.0076745404488,21.3723007605583"
         },
         {
            "key":"date",
            "value":"10/20/2010"
         },
         {
            "key":"mode",
            "value":"TraverseMode (WALK, TRAM, SUBWAY, RAIL, BUS, FERRY, CABLE_CAR, GONDOLA, FUNICULAR, TRANSIT, TRAINISH, BUSISH)"
         },
         {
            "key":"numItineraries",
            "value":"3"
         }
      ]
   }
}

这是我用于第一部分的内容

JSONObject planObject=json.getJSONObject("plan");
            Log.i("date",planObject.get("date").toString());

            JSONObject fromObject=planObject.getJSONObject("from");
            Log.i("from object",fromObject.get("name").toString());
            Log.i("from object",fromObject.get("stopId").toString());
            Log.i("from object",fromObject.get("lon").toString());
            Log.i("from object",fromObject.get("lat").toString());

这是Felix写的例子,它是关于多个“行程”

"itineraries": [
    {"duration": "123456", ... },
    {"duration": "789012", ... }
]

这将是同一个例子,但对于一个:

"itineraries": 
{"duration": "123456", ... },

所以在第二种情况下没有JSONArray所以如果我尝试使用Felix给解析数组的代码,它将返回错误。

所以问题是:检查值是否可以放入JSONArray的方法是什么。是命令optJSONArray(“possibleArrayValues”)!= null使用或者是否有更好的方法然后进行大量的if-then检查?

1 个答案:

答案 0 :(得分:1)

我认为在JSON对象中有多个具有相同名称的键是 legal 。即JSON对象中的键应该形成 set ,而不是列表。

当有更多行程时,你能发布一个例子吗?我打赌它看起来像:

...
"itineraries": [
    {"duration": "123456", ... },
    {"duration": "789012", ... }
]
...

如果 看起来像这样,解析它很容易:

JSONArray itineraries = planObject.getJSONArray("itineraries");
for (int i=0; i < itineraries.length(); i++) {
    Log.i("TAG", itineraries.getJSONObject(i).getString("duration");
}

如果没有,那么您使用的API就会被破坏。要么修复它,要么告诉谁运行它来修复它:)


编辑:现在我们知道了多项响应的样子,以下是解析它的方法:

Object itineraries = planObject.get("itineraries");
if (itineraries instanceof JSONObject) {
    JSONObject itinerary = (JSONObject) itineraries;
    // right now, itinerary is your single item
}
else {
    JSONArray array = (JSONArray) itineraries;
    // do whatever you want with the array of itineraries
}

未经测试,但它应该有效。