티스토리 뷰

Spring

Jackson - No serializer found Exception

구티맨 2022. 4. 25. 09:53

Jackson으로 객체를 직렬화 할 때, 아래와 같이 에러가 발생할 때가 있습니다.

직렬화를 할 때, 객체의 getter를 사용하여 변환을 하는데 이 때 에러가 발생하면 아래와 같은 예외가 발생합니다.

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 
No serializer found for class com.example.springapp.animal.Cat and no properties discovered to create BeanSerializer 
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

 

코드를 보면 Cat 객체를 직렬화 하는데, Cat 클래스에 getter가 없습니다.

이를 해결하는 여러가지 방법을 알아보겠습니다.

public class Cat implements Walk {
    private String name;

    public Cat(String name) {
        this.name = name;
    }
}
public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Cat cat = new Cat("kitty");
        String catString = objectMapper.writeValueAsString(cat);
        System.out.println("catString : " + catString);
}

 

방법 1. Getter 추가

@Getter
public class Cat implements Walk {
    private String name;

    public Cat(String name) {
        this.name = name;
    }
}

 

방법 2. setVisibility

private 필드에도 접근가능 하도록 설정 해줍니다.

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

 

방법 3. @JsonAutoDetect

private 필드에도 접근가능 하도록 설정 해줍니다.

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Cat implements Walk {
   ...
}

 

방법 4. @JsonProperty

필드에 JsonProperty를 선언해 줍니다.( 직렬화를 적용하지 않을 필드에는 @JsonIgnore를 해줘야 합니다. )

public class Cat implements Walk {
    @JsonProperty
    private String name;
    ...
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함