How to iterate a JsonObject (gson)

Floyd picture Floyd · Jan 15, 2015 · Viewed 35.7k times · Source

I have a JsonObject e.g

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

Every JsonObject contains 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:

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 (4711 and "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?",
}

Answer

atish shimpi picture atish shimpi · Jan 15, 2015

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