问题
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 -->
}
}
回答1:
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
回答2:
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);
来源:https://stackoverflow.com/questions/29698258/convert-mapinteger-object-to-json-with-gson