【发布时间】:2019-10-15 13:09:05
【问题描述】:
我正在编写一个通用的 JSON 反序列化,使用 ObjectMapper(com.fasterxml.jackson 库) 函数接收对象类型和集合/映射类型作为参数。
这是我的代码:
// Reading a single object from JSON String
public static <T> Object readObjectFromString(String string, Class<T> type) {
try {
return objectMapper.readValue(string, type);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// Reading a Collection object from JSON String
public static <T> Object readCollectionObjectsFromString(String string, Class<? extends Collection> collectionType, Class<T> type) {
try {
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(collectionType, type);
return objectMapper.readValue(string, typeReference);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// Reading a Map object from JSON String
public static <T> Object readCollectionObjectsFromString(String string, Class<? extends Map> mapType, Class<T> keyType, Class<T> valueType) {
try {
MapType typeReference =
TypeFactory.defaultInstance().constructMapType(mapType, keyType, valueType);
return objectMapper.readValue(string, typeReference);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
但是如果用户需要反序列化一个复杂的嵌套通用对象怎么办,比如:
Map<A,List<Map<B,C>>> nestedGenericObject1
List<Map<A,B>> nestedGenericObject2
Map<List<A>,List<B>> nestedGenericObject3
// etc...
如何将其作为一般解决方案实施?
【问题讨论】:
-
旁注:为什么你从你的方法返回
Object而不是T,例如你的readObjectFromString。现在这些方法似乎很不可用。 -
这是什么
ObjectMapper类型?是从图书馆来的吗?哪一个? -
来自 com.fasterxml.jackson 库的 ObjectMapper
标签: java serialization jackson