gpt4 book ai didi

java - 使用匿名类的 Jackson 反序列化

转载 作者:搜寻专家 更新时间:2023-11-01 01:42:28 25 4
gpt4 key购买 nike

我一整天都在寻找能回答这个问题的东西,但到目前为止我运气不太好。

我的问题很简单:如何使用 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}]:

线程“main”com.fasterxml.jackson.databind.JsonMappingException 中的异常:无法将类 com.foo.test.JacksonTest$1(本地/匿名类型)反序列化为 Bean

编辑 澄清一下,Jackson 和 XStream 都能够序列化该对象。但似乎只有 XStream 能够将对象反序列化回来。所以这个场景可以工作。

最佳答案

在我写这篇文章的时候,Jackson 似乎没有正确地序列化内部类或匿名类。但是,XStream 和 Kryo 等其他软件包可以。

关于java - 使用匿名类的 Jackson 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28418564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com