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

发布于 2024-09-30 10:53:23 字数 4846 浏览 5 评论 0原文

我需要使用 android json 解析器在 android 中解析此响应,但我在任何地方都找不到答案是:

如果例如“行程”可以包含一个或有时多个行程类型的对象,我该如何解析数据? 如果它包含一个,则像这样返回,但如果它包含更多,则以 [] 返回 在这个例子中,“行程”不能放入 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 检查?

i need to parse this response in android using the android json parser but the thing i cant find the answer to anywhere is:

how do i parse the data if for example "itineraries" can contain one or sometimes more objects of the type itinerary?
if it contains one than it is returned like this but if it contains more it is returned with []
with this example "itinerary" cannot be placed into a JsonArray becouse obviously it is not an array. (not placed in [] right?)

how do i parse this? any examples?

  {
   "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"
         }
      ]
   }
}

here is what i use for the first part

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

this is the example Felix wrote and it is about multiple "itineraries"

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

this would be the same example but for one:

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

so in the second case there is no JSONArray so if i try to use the code Felix gave for parsing array it will return a error.

so the question is: what is the way to check if the value can be put in a JSONArray. is The command optJSONArray("possibleArrayValues")!=null used or is there a better method then doing lots of if-then checks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

私藏温柔 2024-10-07 10:53:23

我认为在 JSON 对象中拥有多个同名键是不合法的。即 JSON 对象中的键应该形成一个集合,而不是列表。

行程较多时可以举个例子吗?我敢打赌它会看起来像这样:

...
"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
}

未经测试,但它应该可以工作。

I don't think it's legal to have multiple keys with the same name in a JSON object. I.e. the keys in a JSON object should form a set, not a list.

Can you post an example when there are more itineraries? I bet it would look something like:

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

If it does look like this, parsing it is easy:

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

If it doesn't, the API you're working with is broken. Either fix it or tell whoever runs it to fix it :)


Edit: now that we know how a multiple-item response looks like, here's how to parse it:

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
}

Untested, but it should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文