来自Gson项目的这个链接似乎表明我必须做类似以下的事情来将类型化的Map序列化为JSON:
public static class NumberTypeAdapter
implements JsonSerializer<Number>, JsonDeserializer<Number>,
InstanceCreator<Number> {
public JsonElement serialize(Number src, Type typeOfSrc, JsonSerializationContext
context) {
return new JsonPrimitive(src);
}
public Number deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
return jsonPrimitive.getAsNumber();
} else {
throw new IllegalStateException("Expected a number field, but was " + json);
}
}
public Number createInstance(Type type) {
return 1L;
}
}
public static void main(String[] args) {
Map<String, Number> map = new HashMap<String, Number>();
map.put("int", 123);
map.put("long", 1234567890123456789L);
map.put("double", 1234.5678D);
map.put("float", 1.2345F);
Type mapType = new TypeToken<Map<String, Number>>() {}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(Number.class, new
NumberTypeAdapter()).create();
String json = gson.toJson(map, mapType);
System.out.println(json);
Map<String, Number> deserializedMap = gson.fromJson(json, mapType);
System.out.println(deserializedMap);
}
Run Code Online (Sandbox Code Playgroud)
酷,这是有效的,但它似乎是如此多的开销(一个完整的类型适配器类?).我使用了其他JSON库,如JSONLib,它们允许您以下列方式构建映射:
JSONObject json = new JSONObject();
for(Entry<String,Integer> entry : map.entrySet()){
json.put(entry.getKey(), entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
或者如果我有一个类似以下的自定义类:
JSONObject json = new JSONObject();
for(Entry<String,MyClass> entry : map.entrySet()){
JSONObject myClassJson = JSONObject.fromObject(entry.getValue());
json.put(entry.getKey(), myClassJson);
}
Run Code Online (Sandbox Code Playgroud)
该过程更加手动,但需要的代码更少,并且没有为数字创建自定义类型适配器或在大多数情况下为我自己的自定义类创建的开销.
这是使用Gson序列化地图的唯一方法,还是有人找到了一种方法,可以在上面的链接中击败Gson推荐的内容.
art*_*uro 117
只有TypeToken
部分是必要的(当涉及泛型时).
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");
Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);
System.out.println(json);
Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));
Run Code Online (Sandbox Code Playgroud)
输出:
{"two":"world","one":"hello"}
hello
world
Run Code Online (Sandbox Code Playgroud)
mat*_*rns 91
Map序列化的默认Gson实现使用toString()
密钥:
Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Run Code Online (Sandbox Code Playgroud)
会给:
{
"java.awt.Point[x\u003d1,y\u003d2]": "a",
"java.awt.Point[x\u003d3,y\u003d4]": "b"
}
Run Code Online (Sandbox Code Playgroud)
enableComplexMapKeySerialization
如果要根据默认的Gson规则序列化Map Key,可以使用enableComplexMapKeySerialization.这将返回一组键值对数组:
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Run Code Online (Sandbox Code Playgroud)
将返回:
[
[
{
"x": 1,
"y": 2
},
"a"
],
[
{
"x": 3,
"y": 4
},
"b"
]
]
Run Code Online (Sandbox Code Playgroud)
更多细节可以在这里找到.
在 Gson 2.7.2 中,它就像这样简单
Gson gson = new Gson();
String serialized = gson.toJson(map);
Run Code Online (Sandbox Code Playgroud)