java - Java - 使用 ObjectMapper 反序列化为动态嵌套泛型类型
问题描述
我正在编写一个通用的 JSON 反序列化,使用 ObjectMapper(com.fasterxml.jackson 库)函数接收对象类型和 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...
如何将其作为一般解决方案实施?
解决方案
您可以使用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);
推荐阅读
- python - 管道 - 类型错误:fit_transform() 接受 2 个位置参数,但给出了 3 个
- ios - 在 Cordova iOS 包中找不到 `OBJROOT="$OBJROOT"` 以尝试修复构建错误:xcodebuild:命令失败,退出代码为 65
- mysql - 错误:ER_NO_DB_ERROR:始终使用数据库限定对象引用时未选择数据库(Node.js + MySql)
- jsf - 未找到来自外部 Web 项目的引用组合
- android - Apollo codegen 安装任务上的 Apollo Android 错误
- reactjs - React:我有一些行为适用于包含整个项目的包装器。但我希望我的中央 div 不受这种行为的影响
- java - 基于自定义属性的 Spring Boot SOAP Web 服务的 Keycloak 身份验证
- node.js - 尝试将 API 结果推送到数组但返回为空
- assembly - 共享 RISC-V 图形库的地方
- python - 尝试在 Jupyter 笔记本中运行 pyspark 时出现错误 java.io.IOException:无法连接到