Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<Integer, Object> to JSON with GSON?

Hee Guys,

I'm curious if it is possible to convert a Map to JSON and vica versa with GSON? The object that i'm putting in is already converted to a Object from JSON with GSON.

Object that i'm using looks like this:

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

    public class Location{
        <-- Fields and Getters/Setters -->
    }
}
like image 210
Jordi Sipkens Avatar asked Apr 17 '15 11:04

Jordi Sipkens


2 Answers

Assuming you're using a 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

like image 112
AlexWalterbos Avatar answered Oct 12 '22 18:10

AlexWalterbos


Sounds like you just need to register the type so 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);
like image 20
Numan1617 Avatar answered Oct 12 '22 20:10

Numan1617