programing tip

ObjectMapper를 사용하여 기본 생성자없이 불변 객체를 de / serialize하는 방법은 무엇입니까?

itbloger 2020. 9. 25. 07:37
반응형

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.

참고URL : https://stackoverflow.com/questions/30568353/how-to-de-serialize-an-immutable-object-without-default-constructor-using-object

반응형