日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/8/23 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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去除/序列化不可变对象而不使用默认构造函数?...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。