Android Studio:org.json.JSONObject类型的无法转换为JSONArray

时间:2018-12-09 00:04:58

标签: android json

我收到错误:尝试检索JSON值时,org.json.JSONObject类型无法转换为JSONArray。

        JSONArray jsonarray = new JSONArray(data);

        for(int i = 0; i < jsonarray.length(); i++){


            JSONObject JO = (JSONObject) jsonarray.get(i);
            String id       = JO.getString("languages");

            dataParsed = dataParsed + id;

        }

JSON如下所示(已删除敏感数据)

   {  
   "ip":"",
   "type":"",
   "continent_code":"EU",
   "continent_name":"Europe",
   "country_code":"GB",
   "country_name":"United Kingdom",
   "region_code":"ENG",
   "region_name":"England",
   "city":"",
   "zip":"",
   "latitude":,
   "longitude":,
   "location":{  
      "geoname_id":,
      "capital":"London",
      "languages":[  
         {  
            "code":"en",
            "name":"English",
            "native":"English"
         }
      ],
      "country_flag":"http:\/\/assets.ipstack.com\/flags\/gb.svg",
      "country_flag_emoji":"\ud83c\uddec\ud83c\udde7",
      "country_flag_emoji_unicode":"U+1F1EC U+1F1E7",
      "calling_code":"44",
      "is_eu":true
   }
}

我应该提到我实际上想要检索的数据是语言的名称。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

JSONObject obj = new JSONObject(data);
JSONObject objLocation = obj.getJSONObject("location");
JSONArray arrayLanguage = objLocation.getJSONArray("languages");

for (int i = 0; i < arrayLanguage.length(); i++) {
    JSONObject JO = (JSONObject) arrayLanguage.get(i);
    String id = JO.getString("languages");
    dataParsed = dataParsed + id;
}