我正在使用(com.fasterxml.jackson库的)ObjectMapper编写常规的JSON反序列化 该函数接收对象类型和Collection / map类型作为参数。
这是我的代码:
// 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...
如何将其作为通用解决方案?
答案 0 :(得分:1)
您可以使用TypeReference<T>
:
TypeReference<Map<A, List<Map<B, C>>>> typeReference =
new TypeReference<Map<A, List<Map<B, C>>>>() {};
Map<A, List<Map<B, C>>> data = mapper.readValue(json, typeReference);
如果要将其包装在一个方法中,则可以使用一个方法,例如:
public <T> T parse(String json, TypeReference<T> typeReference) throws IOException {
return mapper.readValue(json, typeReference);
}
TypeReference<Map<A, List<Map<B, C>>>> typeReference =
new TypeReference<Map<A, List<Map<B, C>>>>() {};
Map<A, List<Map<B, C>>> data = parse(json, typeReference);