syd*_*raz 4 java serialization json jackson deserialization
我一整天都在寻找可以解决这个问题的事情,但到目前为止我还没有好运.
我的问题很简单:如何使用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);
}
Run Code Online (Sandbox Code Playgroud)
在我得到异常之前,它的输出是:JSON = ["com.foo.test.JacksonTest $ 1",{"value":5}]:
线程"main"中的异常com.fasterxml.jackson.databind.JsonMappingException:无法将类com.foo.test.JacksonTest $ 1(类型为local/anonymous)反序列化为Bean.
编辑只是为了澄清,Jackson和XStream都能够序列化对象.但只有XStream似乎能够反序列化该对象.因此,这种情况可以起作用.
截至我写这篇文章的时候,杰克逊似乎没有正确地序列化内部类或匿名类.但是,其他软件包如XStream和Kryo也会这样做.
| 归档时间: |
|
| 查看次数: |
4437 次 |
| 最近记录: |