Convert <Integer, Object> map to JSON using GSON?

Hi guys,

I am curious if it is possible to convert a card to JSON and vica versa using GSON? The object that I am inserting is already converted to an object from JSON using GSON.

The object I'm using looks like this:

public class Locations{
    private List<Location> location;
    <-- Getter / Setter --> 

    public class Location{
        <-- Fields and Getters/Setters -->
    }
}
+4
source share
2 answers

Assuming you are using java.util.Map:

Map<Integer, Object> map = new HashMap<>();

map.put(1, "object");

// Map to JSON
Gson gson = new Gson(); // com.google.gson.Gson
String jsonFromMap = gson.toJson(map);
System.out.println(jsonFromMap); // {"1": "object"}

// JSON to Map
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
for (String key : map.keySet()) {
    System.out.println("map.get = " + map.get(key));
}

Source

+9
source

It looks like you just need to register the type so that GSON knows what to do with it:

Gson gson = new Gson();
Type integerObjectMapType = new TypeToken<Map<Integer, Object>>(){}.getType();
Map<Integer, Object> map = new HashMap<>();
map.put(1, new Object());

String json = gson.toJson(map, integerObjectMapType);
System.out.println(json);
0
source

All Articles