HashMap for gson with maps as values

I want to convert the format HashMapto JSONusing this 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 as a result, I have nothing in JSON. Let's say I have something like this in Java:

put("key", HashMap);

after the conversion, my JSON looks like this:

"key" : {}

I want, I want, obviously, something like this:

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

Is this becouse toJson()no more complicated JSON? I think that most likely I'm doing something wrong.

@EDIT

This is how I initialize the map:

put("key", new HashMap<String,String>(){{
                put("key1", "value1");
            }};
+4
source share
1 answer

Wherein:

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

You create a new one AnonymousInnerClasswith instance initializer.

From Gson docs:

Gson . Gson , no-args , .

, instance initializer:

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

Source: https://habr.com/ru/post/1684440/


All Articles