【问题标题】:Looping through gson object in Java?在Java中循环遍历gson对象?
【发布时间】:2014-03-16 21:53:49
【问题描述】:

我目前正在开发一个从名为 CloudMine 的网站获取 JSON 响应的 Android 应用程序。他们的回复通常采用以下格式:

{
    "success": {
        "key1": { "field": "value1" },
        "key2": { "field1": "value1", "field2": "value2" }
    },
    "errors": {
        "key3": { "code": 404, "message": "Not Found" }
    }
}

我目前想遍历“成功”对象中的所有对象,以便访问每个对象中的不同字段。但是,我只被教过如何使用来自 gson API 的 JsonParser。我得到的最接近的是在成功对象上使用 names() 方法,但 Eclipse 对我大喊大叫,因为该方法对于这种类型是未定义的。

感谢任何人能给我的所有帮助。

谢谢!

【问题讨论】:

    标签: android json eclipse gson


    【解决方案1】:

    这对我有用:

    JsonObject myJsonObject = new Gson().fromJson(myJsonString, JsonObject.class);
    
                for (Map.Entry<String, JsonElement> entry : myJsonObject.entrySet()) {
    
                    JsonObject entryObj = entry.getValue().getAsJsonObject();
                }
    

    根据这个问题的公认答案,尽管我已经针对我的用例进行了修改:

    Iterate over JsonObject properties

    【讨论】:

      【解决方案2】:

      这是一个非常简单的代码,它将在“成功”中迭代对象:

      JSONObject json = new JSONObject(responseString);
      JSONObject success = json.getJSONObject("success");
      JSONObject one;
      for(Iterator it=success.keys(); it.hasNext(); ) {
          one = success.getJSONObject((String)it.next());
          //deal with the next object inside your 'success'
      }
      

      【讨论】:

      • 你不只是喜欢没有 cmets 的投票者吗?
      • 很确定这不是 Gson,如问题中所述。
      猜你喜欢
      • 1970-01-01
      • 2020-06-09
      • 2015-06-27
      • 1970-01-01
      • 2020-04-30
      • 2017-06-12
      • 2015-10-31
      • 2014-11-30
      • 1970-01-01
      相关资源
      最近更新 更多