使用GSON将Map <Integer,Object>转换为JSON?

Jor*_*ens 4 android json dictionary object gson

嘻嘻

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

我正在使用的对象如下所示:

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

    public class Location{
        <-- Fields and Getters/Setters -->
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*bos 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));
}
Run Code Online (Sandbox Code Playgroud)

资源