4

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");
            }};
shurrok
  • 795
  • 2
  • 13
  • 43

1 Answers1

1

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");
ByeBye
  • 6,650
  • 5
  • 30
  • 63
  • In the other words, I need to improve my method. Am I right? – shurrok Aug 25 '17 at 08:03
  • Just don't use `instance initializer` because it creates anonymous inner classes which gson cannot serialize – ByeBye Aug 25 '17 at 08:06
  • Yes, that's the simplest solution. But I'm curious if I can change my `JSObject` method to let me use anonymous class – shurrok Aug 25 '17 at 08:10
  • This does not look to be the issue. You are talking about *de*serialization while the question is asking about serialization. – user3151902 Aug 25 '17 at 08:32