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

孤街浪徒 提交于 2019-12-23 12:34:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!