这个链接来自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);
}
很酷并且它能够工作,但是它似乎有太多的开销(整个类型适配器类?)。我已经使用过其他 JSON 库,比如 JSONLib,在以下方式中它们允许你构建一个映射:
JSONObject json = new JSONObject();
for(Entry<String,Integer> entry : map.entrySet()){
json.put(entry.getKey(), entry.getValue());
}
或者如果我有一个自定义类,例如以下内容:
JSONObject json = new JSONObject();
for(Entry<String,MyClass> entry : map.entrySet()){
JSONObject myClassJson = JSONObject.fromObject(entry.getValue());
json.put(entry.getKey(), myClassJson);
}
这个过程更加手动,但是需要的代码更少,并且没有创建自定义数字类型适配器或在大多数情况下为我自己的自定义类适配器的开销。
这是使用Gson序列化Map的唯一方式吗?还是有人找到了一种超越Gson推荐链接中方法的方式呢?