且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Jackson自定义反序列化列表

更新时间:2022-12-11 11:13:00

首先,如果您使用Bean CustomClass上的注释注册了自定义反序列化器,则该反序列化器应处理CustomClass的一个实例而不是一个集合.因此应该定义:

First of all, If you registered your custom deserializer using annotation on the bean CustomClass then the deserializer should handle one instance of CustomClass and not a collection and thus should be defined:

public class MyCustomDeserializer extends JsonDeserializer<CustomClass> {
        @Override
        public CustomClass deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException
        {
            ...
        }
}

现在您可以使用Jackson的类型工厂向映射器传递所需的类型信息

and now you can use Jackson's type factory to pass the mapper the required type information

JavaType customClassCollection = objectMapper.getTypeFactory().constructCollectionType(List.class, CustomClass.class);
List<CustomClass> beanList = (List<CustomClass>)objectMapper.readValue(stringBean, customClassCollection);