gpt4 book ai didi

java - 不使用默认构造函数反序列化 JSON

转载 作者:行者123 更新时间:2023-12-02 09:36:37 26 4
gpt4 key购买 nike

我正在迁移现有的通信层以将 REST 与 JSON 结合使用。以前的框架不需要传输 POJO 的默认构造函数。

我无法对正在传输的模型类进行更改,因此注释不是一个选项。 Mixin 也不是一个选择。它应该是一个中心配置。

这是当前的配置和测试代码:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setDefaultPropertyInclusion(Include.NON_NULL);
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.ANY);
mapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false);

PrivateObject object = new PrivateObject(1234, "test");
String jsonString = mapper.writeValueAsString(object);
PrivateObject result = mapper.readValue(jsonString, PrivateObject.class);

POJO 示例:

public class PrivateObject {
private int id;
private String name;

public PrivateObject(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public String getName() {
return name;
}
}

JSON 示例:

{"id":1234,"name":"test"}

产生的异常:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.softmodeler.common.pojo.PrivateObject` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":1234,"name":"test"}"; line: 1, column: 2]

最佳答案

如果您使用 Java 8 或更高版本,则无需注释或 mixins 即可完成:

  • 编译将-parameters参数传递给javac
  • 在您的依赖项中包含模块 jackson-module-parameter-names 并注册它,例如mapper.registerModule(new ParameterNamesModule());

更多详情here

关于java - 不使用默认构造函数反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459507/

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