Java DTO에서 String으로 된 Json값 변환하기

@ZungTa · 2024-01-22 월요일 · 1 min read

API 연동 작업 도중 API응답이 좀 특이한 경우가 있었다.

예시로 보면 이렇게 JSON 안에 String을 넣어놓은 경우다.

{
  "name": "john",
  "profile": "{\"age\": 10, \"nickname\": \"showman\"}"
}

이럴 경우 DTO를 작성할 때 해당 값의 타입을 String으로 하지 않으면 오류가 발생한다.

public class UserResponseDto {
  String name;
  String profile;
}

하지만 객체로 받는 방법이 있다.

@JsonSetter를 이용해서 set이 될 때 동작을 직접 구성해줄 수 있다.

public class UserResponseDto {
  String name;
  Profile profile;

  @JsonSetter
  public void setProfile(String profileString) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    profile = objectMapper.readValue(profileString, Profile.class);
  }

  public static class Profile {
    Integer age;
    String nickname;
  }
}

References

@ZungTa
I'm a backend developer
© ZungTa Devlog, Built with Gatsby