慎用Collectors.toUnmodifiableList()

693 阅读1分钟

在使用Redis做缓存时,用jackson反序列化List类型的数据序列时报错:

org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unexpected token (START_ARRAY), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.lang.Object)

再查看redis中,数据没有类型标注:

[
    {
        "a": 1
    }
]

而正常的数据应是:

[ "java.util.ArrayList",
 [
  {
   "a" : 1
  }
 ]
]

在使用Java8 Stream时,Collectors选用UnmodifiableList时Jackson不会进行类型标注,而是将其当作Array来表示,不会正常的序列化为ArrayList。在需要序列化的场景时,尽量使用Collectors.toList()