jackson은 기본적으로 프로퍼티 기반이므로 getter, setter 에 적용된다.
@JsonProperty
- 해당 필드를 프로퍼티로 적용한다.
- json으로 변환시 키값 표기를 변경할 수 있다.
@JsonProperty(value="member_id")
String memberId;
@JsonIgnore
- 어노테이션이 적용된 필드는 JSON변환시 적용되지 않는다.
@JsonInclude
- 클래스 레벨에서 json변환에 사용될 설정을 추가할 수 있다.
@JsonInclude(JsonInclude.Include.ALWAYS)
public class Member {
....
}
- JsonInclude.Include.ALWAYS: 모든 값을 json변환시 포함한다.
- JsonInclude.Include.NON_NULL: null인 데이터는 json 변환시 제외한다.
- JsonInclude.Include.NON_ABSENT: null 이거나 Optional 객체 내부의 null인 경우를 제외한다.
- JsonInclude.Include.NON_EMPTY: 컬렉션이 비어있거나, Null, String이 " 인 경우를 제외한다.
- JsonInclude.Include.NON_DEFAULT: NON_EMPTY + primitive타잆이 디폴트값이면 제외한다.(int면 0일때 제외, boolean이 false면 제외 등)
@JsonIgnoreProperties
- 클래스 레벨에 선언할 수 있는 어노테이션 으로 json변환시 무시할 필드명들을 여러개 넣을 수 있다.
@JsonIgnoreProperties({"id", "name"})
public class Member {....}
@JsonPropertyOrder
- json 변환시 순서를 지정한다.
@JsonPropertyOrder({"name", "id"})
public class Member {
private int id;
private String name;
}
//name, id 순으로 json에서 출력되어짐.
@JsonAnyGetter
- 게터 함수로 리턴하는 Map을 key:value 로 필드로써 출력한다.
- 필드에는 적용이 불가능 하다.
public class Member {
private int id;
private String name;
private Map<String, String> map;
@JsonAnyGetter
public Map<String, String> getMap() {
return map;
}
}
//{"id":12,"name":"조세진","map.key1":"map.value1","map.key2":"map.value2"}
@JsonAnySetter
- 해당 어노테이션을 setter 에 적용 시키면 json → Object 변환시 Object에 없는 프로퍼티는 해당 메소드를 통해 Object에 저장될 수 있다.
public static class Member {
private int id;
private String name;
private Map<String, String> map = new HashMap<>();
@JsonAnySetter
public void setMap(String key, String value) {
map.put(key, value);
}
}
//{"id":12,"name":"꿀똥벌레","jackson":"yes","gson":"no!"}
//map 에 jackson, gson 이라는 키값으로 yes, no! 가 각각 저장되어진다.
@JsonSerialize
- json serialize 로직을 커스텀 할때 사용한다.
public class Member {
...
@JsonSerialize(using = CustomSerializer.class)
private Date date;
...
}
class CustomDateSerializer extends StdSerializer<Date> {
private static final long serialVersionUID = 1L;
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(Class<Date> t) {
super(t);
}
@Override
public void serialize(Date value,
JsonGenerator generator, SerializerProvider arg2) throws IOException {
generator.writeString(formatter.format(value));
}
}
@JsonDeserialize
- JsonSerialize의 반대되는 기능으로 json deserialize 로직을 커스텀 할때 사용한다.
'JAVA' 카테고리의 다른 글
JPA @ElementCollection (0) | 2021.05.27 |
---|---|
java annotation (0) | 2021.05.17 |
JPA 캐시 (0) | 2021.04.28 |
JPA 락 처리 (0) | 2021.04.28 |
JPA 성능 최적화 (0) | 2021.04.28 |