我如何让Jackson反序列化到我自己的Array实现中

我如何让Jackson反序列化到我自己的Array实现中

本文介绍了我如何让Jackson反序列化到我自己的Array实现中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出我自己的数组实现MyArray<T>,如何让Jackson知道它,以便它能够从JSON数组反序列化为MyArray<T>?到目前为止,我只收到此异常:

Given my own array implementation MyArray<T>, how can I make it known to Jackson, so that it is able to deserialize from a JSON Array into MyArray<T>? So far I am only getting this exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of MyArray out of START_ARRAY token

推荐答案

正如Dariusz所提到的,利用Array类具有接受常规数组的构造函数这一事实是很好的.

As Dariusz mentioned, it's good to take advantage of the fact that Array class has constructor accepting normal array.

看,如果您使用默认的序列化程序-序列化为JSON的数组如下所示:

Look, if you use default serializer - your array serialized to JSON would look like:

{"items":["item1","item2"],"size":2,"ordered":true}

这显然是在浪费空间,除非您希望保留sizeordered字段.

it's clearly a waste of space, unless you want size and ordered fields to be preserved.

我建议您更改对象序列化的方式,使其看上去更像普通数组,另一方面-反序列化可以再次构建Array对象.

I suggest you changing the way you serialize your object so that it would look more like normal array, on the other end - deserialization can build Array object again.

如果添加以下一对序列化器和反序列化器:

If you add following pair of serializer and deserializer:

SimpleModule module = new SimpleModule();
module.addDeserializer(Array.class, new StdDelegatingDeserializer<>(
    new StdConverter<Object[], Array>() {
        @Override
        public Array convert(Object[] value) {
            return new Array(value);
        }
}));

module.addSerializer(Array.class, new StdDelegatingSerializer(
    new StdConverter<Array, Object>() {
        @Override
        public Object convert(Array value) {
            return value.toArray();
        }
}));

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

您将在这些类型之间进行透明转换

you will have transparent conversion between these types

这篇关于我如何让Jackson反序列化到我自己的Array实现中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:38