gpt4 book ai didi

Java - 使用 ObjectMapper 反序列化为动态嵌套泛型类型

转载 作者:行者123 更新时间:2023-12-02 09:25:08 27 4
gpt4 key购买 nike

我正在使用 ObjectMapper(com.fasterxml.jackson 库)编写通用 JSON 反序列化这些函数接收对象类型和集合/映射类型作为参数。

这是我的代码:

// 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);

关于Java - 使用 ObjectMapper 反序列化为动态嵌套泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58395522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com