首页 > 解决方案 > 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...

如何将其作为一般解决方案实施?

标签: javaserializationjackson

解决方案


您可以使用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);

推荐阅读