17

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?",
}
Imran
  • 12,950
  • 8
  • 64
  • 79
Floyd
  • 391
  • 1
  • 3
  • 10
  • Yes, I could cut the first and last character ("), but this would be rather a sad solution (or not?) – Floyd Jan 15 '15 at 13:34

5 Answers5

13

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("\"",""));
    }
   }
atish shimpi
  • 4,873
  • 2
  • 32
  • 50
4

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

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?

You can also try this (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);
    }
Syed Mauze Rehan
  • 1,125
  • 14
  • 31
3

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

Siddhesh Shirodkar
  • 891
  • 13
  • 16
2

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<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 JsonElement to produce other types.

Paul Benn
  • 1,911
  • 11
  • 26
0

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.

Ted Xu
  • 1,095
  • 1
  • 11
  • 20
  • I want to handle all incoming json (with a key "id" and an additional unknown number of key/value pairs) with just ONE (more or less generic) class, where all key/value pairs where key != "id" are stored in a HashMap. Atm I managed to do so, but every value is wrapped in ". – Floyd Jan 15 '15 at 14:10