使用GSON将Map <integer,object =“”>转换为JSON?</integer,>

时间:2015-04-17 11:46:12

标签: android json object dictionary gson

Hee Guys,

我很好奇是否可以将地图转换为JSON,而使用GSON则反之亦然?我放入的对象已经通过GSON从JSON转换为Object。

我使用的对象如下所示:

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

    public class Location{
        <-- Fields and Getters/Setters -->
    }
}

2 个答案:

答案 0 :(得分:10)

假设您正在使用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

答案 1 :(得分:0)

听起来你只需要注册这个类型,以便GSON知道如何处理它:

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);
相关问题