Link
Today
Total
06-30 13:48
Archives
관리 메뉴

초보개발자 긍.응.성

Jackson Annotation 정리 (4) (General Annotations) 본문

Spring/Jackson

Jackson Annotation 정리 (4) (General Annotations)

긍.응.성 2020. 9. 17. 00:58
반응형

Jackson에서 사용하는 Annotation에 대해 정리한다. Baeldung (Jackson Annotation Example)에 정리된 글을 참고하였다.

4. Jackson General Annotations

4.1 @JsonProperty

@JsonProperty는 필드나 메서드 위에 선언되어 serialize/deserialize 될 때 매핑될 property명을 지정해 준다. API서버에서 가져온 응답이 자바의 명명규칙인 camelCase가 아닐 때 DTO에서 이를 매핑해주기위하여 사용한다.  

메서드 위에 선언될 경우 @JsonSetter와 @JsonGetter의 역할을 한다.

public class MyBean {
	public int id;
	private String name;
	
	@JsonProperty("name")
	public void setTheName(String name) {
		this.name = name;
	}
	
	@JsonProperty("name")
	public String getTheName() {
		return this.name;
	}
}

필드위에 선언될 경우 변수 theName를 name으로 매핑되도록 한다. 

public class MyBean {
	public int id;
	@JsonProperty("name")
	private String theName;

	public void setTheName(String name) {
		this.theName = name;
	}

	public String getTheName() {
		return this.theName;
	}
}
@Test
public void testJsonProperty() throws IOException {
	String json = "{\"id\":1,\"name\":\"changwoo\"}";

	ObjectMapper objectMapper = new ObjectMapper();
	MyBean myBean = objectMapper.readerFor(MyBean.class).readValue(json);

	System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(myBean));
}

/* return */
{
  "id" : 1,
  "name" : "changwoo"
}

 

4.2 @JsonFormat

@JsonFormat은 속성 값 직렬화에 대한 세부 정보를 설정할 수 있다. 가장 많이 함께 사용되는 객체는 java.util.Date이다. Date를 아무 설정 없이 출력하면 1970년 1월 1일부터의 지금까지 1/1000초의 값을 반환한다. 우리가 애플리케이션에서 이 데이터를 날짜 포맷으로 맞추어 사용하려면 매번 SimpleDateFormat을 지정해야하는 불편함이 존재한다. @JsonFormat 애노테이션을 통해 직렬화 과정에서 어떠한 pattern으로 출력될지를 지정해줄 수 있다.

shape=JsonFormat.Shape.Number로 지정하면 timeMillis의 값으로 출력된다.
public class EventWithFormat {
	public String name;

	@JsonFormat(
		shape = JsonFormat.Shape.STRING,
		pattern = "yyyy-MM-dd hh:mm:ss")
	public Date eventDate;

	public EventWithFormat(String name, Date eventDate) {
		this.name = name;
		this.eventDate = eventDate;
	}
}
@Test
public void testJsonFormat() throws ParseException, JsonProcessingException {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

	String toParse = "2020-09-17 00:26:00";
	Date date = sdf.parse(toParse);
	EventWithSerializer event = new EventWithSerializer("party", date);

	System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(event));
}
/* @JsonFormat 적용 전*/
{
  "name" : "party",
  "eventDate" : 1600302360000
}

/* @JsonFormat 적용 후 */
{
  "name" : "party",
  "eventDate" : "2020-09-17 09:26:00"
}

 

4.3 @JsonUnwrapped

@JsonUnwrapped는 property를 serialize/deserialize 과정에서 평탄화(flattened)한다. 

public class UnwrappedUser {
	public int id;

	@JsonUnwrapped
	public Name name;

	public UnwrappedUser(int id, Name name) {
		this.id = id;
		this.name = name;
	}

	public static class Name {
		public String firstName;
		public String lastName;

		public Name(String firstName, String lastName) {
			this.firstName = firstName;
			this.lastName = lastName;
		}
	}
}
@Test
public void testJsonUnwrapped() throws JsonProcessingException {
	UnwrappedUser.Name name = new UnwrappedUser.Name("Son", "changwoo");
	UnwrappedUser user = new UnwrappedUser(1, name);

	System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(user));
}
/* @JsonUnwrapped 적용 전 */
{
  "id" : 1,
  "name" : {
    "firstName" : "Son",
    "lastName" : "changwoo"
  }
}

/* @JsonUnwrapped 적용 전 */
{
  "id" : 1,
  "firstName" : "Son",
  "lastName" : "changwoo"
}
반응형
Comments