Java 如何迭代 JSONObject (gson)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27964498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:22:27  来源:igfitidea点击:

How to iterate a JSONObject (gson)

javajsongsonjson-deserialization

提问by Floyd

I have a JsonObject e.g

我有一个 JsonObject 例如

JsonObject jsonObject = {"keyInt":2,"keyString":"val1","id":"0123456"}

Every JsonObjectcontains a "id"entry, but the number of other key/value pairs is NOT determined, so I want to create create an object with 2 attributes:

每个都JsonObject包含一个"id"条目,但其他键/值对的数量未确定,因此我想创建一个具有 2 个属性的对象:

class myGenericObject {
  Map<String, Object> attributes;
  String id;
}

So I want my attributes map to look like this:

所以我希望我的属性映射看起来像这样:

"keyInt" -> 4711
"keyStr" -> "val1"

I found this solution

我找到了这个解决方案

Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
  attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
}

but the values are enclosed by ""

但值被包围 ""

"keyInt" -> "4711"
"keyStr" -> ""val1""

How to get the plain values (4711and "val1")?

如何获得普通值(4711"val1")?

Input data:

输入数据:

{
  "id": 0815, 
  "a": "a string",
  "b": 123.4,
  "c": {
    "a": 1,
    "b": true,
    "c": ["a", "b", "c"]
  }
}

or

或者

{
  "id": 4711, 
  "x": false,
  "y": "y?",
}

回答by atish shimpi

replace "" with blank.

将“”替换为空白。

   Map<String, Object> attributes = new HashMap<String, Object>();
   Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
   for(Map.Entry<String,JsonElement> entry : entrySet){
    if (! nonProperties.contains(entry.getKey())) {
      properties.put(entry.getKey(), jsonObject.get(entry.getKey()).replace("\"",""));
    }
   }

回答by Ted Xu

I am not quite sure why you want to do manual manipulation in the first place. GSON decode will simply leave those absent key/value pairs as default value (zero,null). And then you can process as you want.

我不太确定你为什么要首先进行手动操作。GSON 解码只会将那些不存在的键/值对保留为默认值(零,空)。然后您可以根据需要进行处理。

回答by Syed Mauze Rehan

How are you creating your JsonObject? Your code works for me. Consider this

你是如何创建你的 JsonObject 的?你的代码对我有用。考虑这个

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
...
...
...
try{
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyInt", 2);
        jsonObject.addProperty("keyString", "val1");
        jsonObject.addProperty("id", "0123456");

        System.out.println("json >>> "+jsonObject);

        Map<String, Object> attributes = new HashMap<String, Object>();
        Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
        for(Map.Entry<String,JsonElement> entry : entrySet){
          attributes.put(entry.getKey(), jsonObject.get(entry.getKey()));
        }

        for(Map.Entry<String,Object> att : attributes.entrySet()){
            System.out.println("key >>> "+att.getKey());
            System.out.println("val >>> "+att.getValue());
            } 
    }
    catch (Exception ex){
        System.out.println(ex);
    }

And it is working fine. Now I am interested in knowing how you created that JSON of yours?

它工作正常。现在我有兴趣知道您是如何创建您的 JSON 的?

You can also try this (JSONObject)

你也可以试试这个(JSONObject)

import org.json.JSONObject;
...
...
...
try{
        JSONObject jsonObject = new JSONObject("{\"keyInt\":2,\"keyString\":\"val1\",\"id\":\"0123456\"}");
        System.out.println("JSON :: "+jsonObject.toString());

        Iterator<String> it  =  jsonObject.keys();
         while( it.hasNext() ){
             String key = it.next();
             System.out.println("Key:: !!! >>> "+key);
             Object value = jsonObject.get(key);
             System.out.println("Value Type "+value.getClass().getName());
            }
    }
    catch (Exception ex){
        System.out.println(ex);
    }

回答by Siddhesh Shirodkar

Just make following changes...

只需进行以下更改...

Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
 attributes.put(entry.getKey(), jsonObject.get(entry.getKey()).getAsString());
}

"getAsString" will do the magic for u

“getAsString” 会为你带来魔力

回答by Paul Benn

Your Map values are JsonElements. Whenever you print a JsonElement(e.g. using a debugger) its toString()method will be called - and since a JsonElementhas many implementing classes the default toStringimplementation wraps the value in quotes to ensure correct JSON. To get the value as a normal, unwrapped String, simply call getAsString():

您的 Map 值是JsonElements。每当您打印 a JsonElement(例如使用调试器)时,它的toString()方法将被调用 - 由于 aJsonElement有许多实现类,因此默认toString实现将值包装在引号中以确保正确的 JSON。要获取正常的未包装值String,只需调用getAsString()

JsonElement elem;
// ...
String value = elem.getAsString();

With your example:

以你的例子:

Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for(Map.Entry<String,JsonElement> entry : entrySet){
  attributes.put(entry.getKey(), jsonObject.get(entry.getKey()).getAsString());
}

Note there are many other methods you can call on a JsonElementto produce other types.

请注意,您可以调用许多其他方法JsonElement来生成其他类型。