【问题标题】:Java - deserialization into dynamic nested generic types with ObjectMapperJava - 使用 ObjectMapper 反序列化为动态嵌套泛型类型
【发布时间】: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


【解决方案1】:

你可以使用TypeReference&lt;T&gt;:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2013-01-08
相关资源
最近更新 更多