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的用戶。
所以我的問題是:我可以以某種方式去/不序列化不變的對象沒有默認的構造函數?
總結
以上是生活随笔為你收集整理的java 不允许默认构造_java – 如何使用ObjectMapper去除/序列化不可变对象而不使用默认构造函数?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分解连续自然数的和_小学奥数各年级经典题
- 下一篇: cnetos7 mysql5.6 utf