从 JSONArray 获取 JSONObject?

Getting a JSONObject from a JSONArray?

我正在尝试从 JSON 数组中获取 JSON 对象。当我执行 Log.i 显示 JSONArray 的值并且具有我想要的 JSONObject 时。问题是当我尝试获取此 JSON 对象时,抛出异常显示:No value for Local or No value for TipoLocal。 Local 和 TipoLocal 是 JSONObject into JSONArray.

我该怎么做?

JSON

{"Retorno":[
{"Local":{"id":"1","nome":"Vovo Landa","telefone":"3333333","celular":"44444","endereco":"Rua 46 a","numero":"025","bairro":"bairro","email":"email"}},
{"TipoLocal":{"id":"1","tipo":"Pizzaria"}}
]}

JSON对象

try{
   Gson gson = new Gson();
   JSONArray retorno = obj.getJSONArray("Retorno");

   if(retorno.length() > 0){
         for(int x = 0; x < retorno.length(); x++){
              JSONObject jsoObject = retorno.getJSONObject(x);
              JSONObject jsoLocal = jsoObject.getJSONObject("Local");
              JSONObject jsoTipoLocal = jsoObject.getJSONObject("TipoLocal");
         }
    }
}catch (JSONException e) {
      Log.e("JSONException->:", "getLocais in LocalDAO: " + e.getLocalizedMessage());
}

当没有发现值错误发生时,他们可能会遵循原因

1) 如果您通过 Internet 连接,请检查您的网络连接是否正常工作。

2) 在 AndroidManifest.xml 文件中声明 Internet 权限。

3) 检查您是否获得了正确的元素,如果您正在调用 result.getJsonObject(),那么请确保您正在尝试获取 JsonObject 而不是 JsonArray。

4) 如果您在 Android 中找不到任何值,请检查您是否从 android 端和服务器端拼写正确的单词 例如,如果您在服务器中声明了 "City",那么请确保在 android 中,否则它应该是 "City" 而不是 "city".

5) 如果您要在 JsonArray 上添加 JsonObject,请检查 JsonObject 是否已添加到服务器端的 JsonArray 上。

6) 检查 LogCat 中的实际异常,它会告诉您实际的事情,为什么您没有获得值

希望对您有所帮助

更改此部分:

for(int x = 0; x < retorno.length(); x++){
    JSONObject jsoObject = retorno.getJSONObject(x);
    JSONObject jsoLocal = jsoObject.getJSONObject("Local");
    JSONObject jsoTipoLocal =jsoObject.getJSONObject("TipoLocal");
}

for(int x = 0; x < retorno.length(); x++){
    JSONObject jsoObject = retorno.getJSONObject(x);

    if(jsoObject.has("Local")) {      
        JSONObject jsoLocal = jsoObject.getJSONObject("Local");
    }
    if(jsoObject.has("TipoLocal")) {
        JSONObject jsoTipoLocal = jsoObject.getJSONObject("TipoLocal");
    }
}