Gson 项目中的 This 链接似乎表明我必须执行以下操作才能将类型化的 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,它们让您可以通过以下方式构建 map :
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);
}
该过程更加手动,但需要的代码更少,并且没有为 Number 或在大多数情况下为我自己的自定义类创建自定义类型适配器的开销。 。
这是用 Gson 序列化 map 的唯一方法吗,或者有没有人找到一种优于 Gson 在上面链接中推荐的方法。
最佳答案
只有 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"));
输出:
{"two":"world","one":"hello"}
hello
world
关于java - Gson:有没有更简单的方法来序列化 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8360836/