티스토리 뷰

모든 소스는 여기서 확인하실 수 있습니다.

커스텀 애노테이션 (@JacksonAnnotationInside)

@JacksonAnnotationInside 애노테이션을 사용하여 커스텀 애노테이션을 정의할 수 있습니다.

package io.lcalmsky.jackson.domain.annotation;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name", "id", "date"})
public @interface CustomAnnotation {
}
package io.lcalmsky.jackson.domain;

import io.lcalmsky.jackson.domain.annotation.CustomAnnotation;
import lombok.Data;

import java.util.Date;

@CustomAnnotation
@Data
public class BeanWithCustomAnnotation {
    private int id;
    private String name;
    private Date date;
}
package io.lcalmsky.jackson.domain;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;

public class BeanWithCustomAnnotationTests {
    @Test
    @DisplayName("CustonAnnotation을 사용하여 직렬화하기")
    public void givenCustomAnnotationProvided_whenSerialize_thenCorrect() throws JsonProcessingException {
        // given
        BeanWithCustomAnnotation bean = new BeanWithCustomAnnotation();
        bean.setId(1);
        bean.setName("name");
        bean.setDate(null);

        // when
        String json = new ObjectMapper().writeValueAsString(bean);

        // then
        assertAll(
                () -> assertThat(json, containsString("id")),
                () -> assertThat(json, containsString("name")),
                () -> assertThat(json, not(containsString("date")))
        );

        // log
        System.out.println(json);
    }
}

JUnit Test 결과

댓글