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 -->
}
}
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With