How to iterate a JsonObject (gson)

前端 未结 5 1150
有刺的猬
有刺的猬 2021-02-19 08:50

I have a JsonObject e.g

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

Every JsonObject contains

5条回答
  •  灰色年华
    2021-02-19 09:23

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

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

    With your example:

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

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

提交回复
热议问题