如何迭代JSONObject(gson)

Flo*_*oyd 10 java json gson json-deserialization

我有一个JsonObject例如

JsonObject jsonObject = {"keyInt":2,"keyString":"val1","id":"0123456"}
Run Code Online (Sandbox Code Playgroud)

每个JSONObject都包含一个"id"条目,但是没有确定其他键/值对,所以我想创建一个具有2个属性的对象:

class myGenericObject {
  Map<String, Object> attributes;
  String id;
}
Run Code Online (Sandbox Code Playgroud)

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

"keyInt" -> 4711
"keyStr" -> "val1"
Run Code Online (Sandbox Code Playgroud)

我找到了这个解决方案

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()));
}
Run Code Online (Sandbox Code Playgroud)

但是值被""括起来

"keyInt" -> "4711"
"keyStr" -> ""val1""
Run Code Online (Sandbox Code Playgroud)

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

输入数据:

{
  "id": 0815, 
  "a": "a string",
  "b": 123.4,
  "c": {
    "a": 1,
    "b": true,
    "c": ["a", "b", "c"]
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

{
  "id": 4711, 
  "x": false,
  "y": "y?",
}
Run Code Online (Sandbox Code Playgroud)

ati*_*mpi 8

用空白替换"".

   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("\"",""));
    }
   }
Run Code Online (Sandbox Code Playgroud)