杰克逊用匿名类反序列化 [英] Jackson deserialization with anonymous classes

查看:550
本文介绍了杰克逊用匿名类反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一整天都在寻找可以解决这个问题的事情,但到目前为止我还没有太多运气。

I have been searching all day for something that answers this, but I have not had a lot of luck thus far.

我的问题很简单:如何使用Jackson正确反序列化匿名对象。

My question is straightforward: how do I deserialize an anonymous object correctly using Jackson.

private interface Interface1
{
    int getValue();
}

public static void testAnonymousObject() throws IOException
{
    ObjectMapper mapper = new ObjectMapper();

    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    Interface1 testObject = new Interface1()
    {
        private final int value = 5;

        @Override
        public int getValue()
        {
           return value;
        }
    };

    String json = mapper.writeValueAsString(testObject);
    System.out.println("JSON = " + json);

    Interface1 received = (Interface1) mapper.readValue(json, Object.class);
    System.out.println(received);
}

这个输出是:JSON = [com.foo.test。在获得异常之前,JacksonTest $ 1,{value:5}]:

The output of this is: JSON = ["com.foo.test.JacksonTest$1",{"value":5}] before I get an exception:

线程maincom.fasterxml.jackson.databind中的异常。 JsonMappingException:无法将类com.foo.test.JacksonTest $ 1(类型为local / anonymous)反序列化为Bean

EDIT 为了澄清,Jackson和XStream都能够序列化该对象。但只有XStream似乎能够反序列化该对象。所以这种情况可以起作用。

EDIT Just to clarify, both Jackson and XStream are able to serialize the object. But only XStream seems to be able to deserialize the object back. So this scenario can be made to work.

推荐答案

截至我写这篇文章的时候,杰克逊似乎没有序列化内部类或匿名类正确。然而,其他包如XStream和Kryo​​也会这样做。

As of the time I am writing this, it seems that Jackson does not serialize inner classes or anonymous classes correctly. Other packages such as XStream and Kryo, do however.

这篇关于杰克逊用匿名类反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆