如何迭代 JsonObject (gson)

2022-09-03 13:51:37

我有一个JsonObject,例如

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

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

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

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

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

我找到了这个解决方案

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

但值由""

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

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

输入数据:

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

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

答案 1

将 “” 替换为空白。

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

答案 2

你如何创建你的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);
    }

而且它工作正常。现在我很想知道你是如何创建你的JSON的?

你也可以试试这个(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);
    }