【问题标题】:Getting a JSONObject from a JSONArray?从 JSONArray 获取 JSONObject?
【发布时间】:2015-02-22 02:13:48
【问题描述】:

我正在尝试从 JSONArray 中获取 JSONObject。当我做 Log.i 显示 JSONArray 的值并拥有我想要的 JSONObject 时。问题是当我尝试获取此 JSONObject 时,会引发异常显示:No value for Local or No value for TipoLocal。 Local 和 TipoLocal 都是 JSONObject 转换成 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"}}
]}

JSONObject

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

【问题讨论】:

    标签: android json jsonobject


    【解决方案1】:

    更改此部分:

    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");
        }
    }
    

    【讨论】:

    • 在第一个 JSONObject 中你有 JUST "Local" 而在第二个中你有 JUST "TipoLocal" ,但是在循环中你同时得到两个对象
    【解决方案2】:

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

    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 中的实际异常,它会告诉你为什么没有得到值的实际情况

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多