Jackson 2.2.x:递归反序列化失败了,为什么?

时间:2014-10-31 13:07:06

标签: java json recursion jackson json-deserialization

确切地说,这是杰克逊2.2.3。

反序列化过程非常复杂,因为根据我反序列化的JSON值的类型,类会发生变化:

  • 基础,抽象类是JsonMergePatch;
  • 当JSON值不是JSON对象时,我反序列化为NonObjectMergePatch;
  • 否则,我递归反序列化为ObjectMergePatch

这是代码(&#34简称导入;简洁);首先,JsonMergePatch

@JsonDeserialize(using = JsonMergePatchDeserializer.class)
public abstract class JsonMergePatch
    implements JsonSerializable
{
    public abstract JsonNode apply(final JsonNode input)
        throws JsonPatchException;
}

NonObjectMergePatch

final class NonObjectMergePatch
    extends JsonMergePatch
{
    private final JsonNode node;

    NonObjectMergePatch(@Nonnull final JsonNode node)
    {
        this.node = Preconditions.checkNotNull(node);
    }

    @Override
    public JsonNode apply(final JsonNode input)
        throws JsonPatchException
    {
        return null; // TODO!
    }

    @Override
    public void serialize(final JsonGenerator jgen,
        final SerializerProvider provider)
        throws IOException, JsonProcessingException
    {
        jgen.writeTree(node);
    }

    @Override
    public void serializeWithType(final JsonGenerator jgen,
        final SerializerProvider provider, final TypeSerializer typeSer)
        throws IOException, JsonProcessingException
    {
        serialize(jgen, provider);
    }
}

ObjectMergePatch

final class ObjectMergePatch
    extends JsonMergePatch
{
    private final Set<String> removedMembers;
    private final Map<String, JsonMergePatch> modifiedMembers;

    ObjectMergePatch(final Set<String> removedMembers,
        final Map<String, JsonMergePatch> modifiedMembers)
    {
        this.removedMembers = ImmutableSet.copyOf(removedMembers);
        this.modifiedMembers = ImmutableMap.copyOf(modifiedMembers);
    }

    @Override
    public JsonNode apply(final JsonNode input)
        throws JsonPatchException
    {
        return null;
    }

    @Override
    public void serialize(final JsonGenerator jgen,
        final SerializerProvider provider)
        throws IOException, JsonProcessingException
    {
        jgen.writeStartObject();

        /*
         * Write removed members as JSON nulls
         */
        for (final String member: removedMembers)
            jgen.writeNullField(member);

        /*
         * Write modified members; delegate to serialization for writing values
         */
        for (final Map.Entry<String, JsonMergePatch> entry:
            modifiedMembers.entrySet()) {
            jgen.writeFieldName(entry.getKey());
            entry.getValue().serialize(jgen, provider);
        }

        jgen.writeEndObject();
    }

    @Override
    public void serializeWithType(final JsonGenerator jgen,
        final SerializerProvider provider, final TypeSerializer typeSer)
        throws IOException, JsonProcessingException
    {
        serialize(jgen, provider);
    }
}

最后,自定义反序列化器:

final class JsonMergePatchDeserializer
    extends JsonDeserializer<JsonMergePatch>
{
    @Override
    public JsonMergePatch deserialize(final JsonParser jp,
        final DeserializationContext ctxt)
        throws IOException, JsonProcessingException
    {
        /* FAILS HERE */
        final JsonNode node = jp.readValueAsTree();
        /*
         * Not an object: the simple case
         */
        if (!node.isObject())
            return new NonObjectMergePatch(node);

        /*
         * The complicated case...
         *
         * We have to build a set of removed members, plus a map of modified
         * members.
         */

        final Set<String> removedMembers = Sets.newHashSet();
        final Map<String, JsonMergePatch> modifiedMembers = Maps.newHashMap();
        final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();

        Map.Entry<String, JsonNode> entry;

        while (iterator.hasNext()) {
            entry = iterator.next();
            if (entry.getValue().isNull())
                removedMembers.add(entry.getKey());
            else {
                final JsonMergePatch value 
                    = deserialize(entry.getValue().traverse(), ctxt);
                modifiedMembers.put(entry.getKey(), value);
            }            
        }

        return new ObjectMergePatch(removedMembers, modifiedMembers);
    }

    /*
     * This method MUST be overriden... The default is to return null, which is
     * not what we want.
     */
    @Override
    public JsonMergePatch getNullValue()
    {
        return new NonObjectMergePatch(NullNode.getInstance());
    }
}

只要反序列化的JSON不是对象,我就编写了可以正常运行的编码测试;当它是一个对象时,我递归调用deserialize()方法来反序列化对象成员值......但是从解析器中读取值失败(上面标记为/* FAILS HERE */),但有以下异常:

java.lang.IllegalStateException: No ObjectCodec defined for the parser, can not deserialize JSON into JsonNode tree
    at com.fasterxml.jackson.core.JsonParser.readValueAsTree(JsonParser.java:1352)
    at com.github.fge.jsonpatch.rfc7386.JsonMergePatchDeserializer.deserialize(JsonMergePatchDeserializer.java:67)
    at com.github.fge.jsonpatch.rfc7386.JsonMergePatchDeserializer.deserialize(JsonMergePatchDeserializer.java:92)
    at com.github.fge.jsonpatch.rfc7386.JsonMergePatchDeserializer.deserialize(JsonMergePatchDeserializer.java:36)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
    at com.github.fge.jsonpatch.rfc7386.SerializationTest.objectSerDeserWorksCorrectly(SerializationTest.java:102)

为什么呢?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

嗯,当谷歌搜索时,我偶然发现a previous question of mine并得出答案;但是我的话很难看......

正如异常所述,问题是JsonParser实例没有关联的ObjectCodec。所以,我们必须用一个喂它;这里的问题是为什么这不是自动完成的......

因此,在自定义反序列化器中,我声明了一个新的ObjectCodec

// JacksonUtils is a class of mine; the method returns an ObjectMapper,
// which extends ObjectCodec
private static final ObjectCodec CODEC = JacksonUtils.newMapper();

.deserialize()方法中,我这样做:

jp.setCodec(CODEC);

它有效。

但它很难看。太糟糕了。它是可怕的。我想要一个更好的解决方案:/