gpt4 book ai didi

java - 如何使用 ObjectMapper 在没有默认构造函数的情况下反/序列化不可变对象(immutable对象)?

转载 作者:IT老高 更新时间:2023-10-28 11:44:41 26 4
gpt4 key购买 nike

我想使用 com.fasterxml.jackson.databind.ObjectMapper 序列化和反序列化不可变对象(immutable对象)。

不可变类看起来像这样(只有 3 个内部属性、getter 和构造函数):

public final class ImportResultItemImpl implements ImportResultItem {

private final ImportResultItemType resultType;

private final String message;

private final String name;

public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}

public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}

@Override
public ImportResultItemType getResultType() {
return this.resultType;
}

@Override
public String getMessage() {
return this.message;
}

@Override
public String getName() {
return this.name;
}
}

但是当我运行这个单元测试时:

@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);

//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}

我得到了这个异常(exception):

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here

这个异常要求我创建一个默认构造函数,但这是一个不可变对象(immutable对象),所以我不想拥有它。它将如何设置内部属性?这会完全混淆 API 的用户。

所以我的问题是:我可以在没有默认构造函数的情况下以某种方式反序列化不可变对象(immutable对象)吗?

最佳答案

要让 Jackson 知道如何创建反序列化对象,请使用 @JsonCreator@JsonProperty构造函数的注释,如下所示:

@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name,
@JsonProperty("resultType") ImportResultItemType resultType,
@JsonProperty("message") String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}

关于java - 如何使用 ObjectMapper 在没有默认构造函数的情况下反/序列化不可变对象(immutable对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30568353/

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