Jackson Annotation

  • Jackson은 json 라이브러리입니다.
  • json뿐만아니라 xml, yaml 등 다양한 형식의 데이터도 지원한다.
  • Spring API서버에서 거의 필수적으로 사용되기때문에 한번 정리해봤다.
  • Spring 3.2버전부터 jackson 라이브러리가 지원된다. (따로 dependency 안받아도 됨)

Jackson Annotation 사용법 정리글

2. Jackson Deserialization Annotation

  • Serialization과 반대로 Json을 객체로 변경하는것을 역직렬화 라고 한다.

2.1 @JsonCreator

  • Json을 Object의 속성(변수)에 매핑될 때 매칭되지 않는 속성에 매핑할때 쓰인다.
  • 메서드나 생성자에 사용가능하다.
{
    "id":1,
    "yourName":"chan"
}
public class BeanWithCreator {
    public int id;
    public String name;

    @JsonCreator
    public BeanWithCreator(@JsonProperty("id") int id, @JsonProperty("yourName") String name) {
        this.id = id;
        this.name = name;
    }
}

2.2 @JacksonInject

  • Json 데이터를 역직렬화 할때 사용하는게 아닌 주입시킬때 사용된다.
  • 메서드, 변수 , 매개변수에 사용 가능
{
  "name": "chan"
}
// id 값을 넣을때 InjectableValues 객체 사용
public static class BeanWithInject {
    @JacksonInject
    public int id;

    public String name;
}

2.3 @JsonAnySetter

  • @JsonAnygetter 와 반대로 Map Type 속성을 역직렬화 할때 쓰인다.
  • 메서드, 변수에 사용 가능
{
    "name":"chan",
    "attr2":"val2",
    "attr1":"val1"
}
public class ExtendableBean {
    public String name;
    private Map<String, String> properties;

    @JsonAnySetter
    public void add(String key, String value) {
        properties.put(key, value);
    }
}

2.4 @JsonSetter

  • @JsonGetter 와 반대로 setter 지정할때 쓰인다.
  • 메서드, 변수, 매개변수에 사용 가능
{
  "id": 1,
  "name": "chan"
}
public class MyBean {
    public int id;
    private String name;

    @JsonSetter("name")
    public void setYourName(String name) {
        this.name = name;
    }
}

2.5 @JsonDeserialize

  • @JsonSerialize 와 반대로 커스텀하게 역직렬화 할때 쓰인다.
  • 클래스, 메서드, 변수, 매개변수에 사용 가능
{
    "name":"chan",
    "eventDate":"2019-12-15 09:00:00"
}
public class EventWithSerializer {
    public String name;

    @JsonDeserialize(using = CustomDateDeserializer.class)
    public Date eventDate;
}

public class CustomDateDeserializer extends StdDeserializer<Date> {

    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public CustomDateDeserializer() {
        this(null);
    }

    public CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {

        String date = jsonparser.getText();
        try {
            return formatter.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

2.6 @JsonAlias

  • 역직렬화 할때 하나 이상의 이름을 지정할때 사용된다.
  • 필드, 메서드, 매개변수에 사용 가능
// fName대신 f_name 도 매핑가능
{
    "fName": "John",
    "lastName": "Green"
}
public class AliasBean {
    @JsonAlias({ "fName", "f_name" })
    private String firstName;   
    private String lastName;
}
참고 + 출처
chanhee.kim's profile image

chanhee.kim

2019-12-15 16:05

Read more posts by this author