반응형
ObjectMapper를 사용하여 기본 생성자없이 불변 객체를 de / serialize하는 방법은 무엇입니까?
com.fasterxml.jackson.databind.ObjectMapper를 사용하여 불변 개체를 직렬화 및 역 직렬화하고 싶습니다.
불변 클래스는 다음과 같습니다 (단지 3 개의 내부 속성, 게터 및 생성자).
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 사용자를 완전히 혼란스럽게 할 것입니다.
그래서 내 질문은 : 어떻게 든 기본 생성자없이 불변 객체를 de / serialize 할 수 있습니까?
Jackson에게 deserialization을위한 개체를 만드는 방법을 알리려면 다음 @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;
}
You can use a private default constructor, Jackson will then fill the fields via reflection even if they are private final.
EDIT: And use a protected/package-protected default constructor for parent classes if you have inheritance.
반응형
'programing tip' 카테고리의 다른 글
git show 줄을 추가하고 줄을 변경하고 줄을 제거하는 방법이 있습니까? (0) | 2020.09.25 |
---|---|
손상된 git 저장소를 수정하는 방법은 무엇입니까? (0) | 2020.09.25 |
Postgresql 집계 배열 (0) | 2020.09.25 |
사람들이 CloudInit를 사용하는 대신 Amazon Cloud Formation에서 Puppet / Chef를 사용하는 이유는 무엇입니까? (0) | 2020.09.25 |
Perl에서 << 'm'= ~ m >> 구문은 무엇을 의미합니까? (0) | 2020.09.25 |