java 不允许默认构造_java – 如何使用ObjectMapper去除/序列化不可变对象而不使用默认构造函数?...

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

不可变类看起来像这样(只有3个内部属性,getter和constructor):

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);

}

我得到这个例外:

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

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

所以我的问题是:我可以以某种方式去/不序列化不变的对象没有默认的构造函数?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值