shurrok
shurrok

Reputation: 831

HashMap to gson with maps as values

I want to convert HashMap to JSON format using this kind of method:

public String JSObject(Object object) {
        Gson gson = new Gson();
        return gson.toJson(object);
}

But the problem is that when my HashMap has another HashMap as a key in the result I've got nothing in the JSON. Let's say I've got something like this in Java:

put("key", HashMap);

after conversion my JSON looks like this:

"key" : {}

Want I want is obviously some kind of these:

"key" : {
    "key1" : "value1",
    "key2" : "value2"
}

Is this becouse toJson() doesn't support more complicated JSON's ? I think that's more probably me doing something wrong.

@EDIT

This is how I initialize the map:

put("key", new HashMap<String,String>(){{
                put("key1", "value1");
            }};

Upvotes: 4

Views: 929

Answers (1)

ByeBye
ByeBye

Reputation: 6946

With this:

final HashMap<String, String> value = new HashMap<String, String>(){{
    put("key1", "value1");
}};

You are creating new AnonymousInnerClass with instance initializer.

From Gson docs :

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization.

Just change you map to not use instance initializer:

final Map<String, String> value = new HashMap<>();
value.put("key", "value");

Upvotes: 1

Related Questions