嗨,大家好,
我想知道是否可以使用GSON将Map转换为JSON,反之亦然?我传入的对象已经使用GSON从JSON转换为对象。
我正在使用的对象如下所示:
public class Locations{
private List<Location> location;
<-- Getter / Setter -->
public class Location{
<-- Fields and Getters/Setters -->
}
}
嗨,大家好,
我想知道是否可以使用GSON将Map转换为JSON,反之亦然?我传入的对象已经使用GSON从JSON转换为对象。
我正在使用的对象如下所示:
public class Locations{
private List<Location> location;
<-- Getter / Setter -->
public class Location{
<-- Fields and Getters/Setters -->
}
}
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));
}
TypeToken<Map<String, String>>
更改为 TypeToken<Map<Integer, String>>
,并将 map
的类型从 Map<String, String>
更改为 Map<Integer, String>
。然后,for 循环中的 key
类型更改为 Integer key
,您可以像上面的示例一样使用 map.get(key)
。希望这有所帮助,如果有问题请告诉我。 - AlexWalterbosGson 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);