Backend/Spring Framework

[Spring Boot] JSON 원하는 필드만 deserialize 하기

mopil 2023. 9. 23. 13:15
반응형

간혹 어플리케이션 외부에서 읽어오는 JSON 데이터 (외부 API나 JSON 파일 등)에서 JSON 포맷과 필드가 복잡한 경우가 많다.

 

이 경우 원하는 필드만 읽을 수 있도록 할 수도 있는데, 

 

스프링 부트에서 기본적으로 내장되어있는 Jackson 라이브러리 설정을 다음과 같이 변경한다.

 

@Configuration
class JacksonConfig {
    @Bean
    fun objectMapper() = ObjectMapper().apply {
            configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    }
}

 

예시로 대강 이런 JSON 파일을 읽어온다고 가정해보자

{
  "SJML": {
    "header": {
      "identifier": "텍스트_구어체 말뭉치 구축_0001404391",
      "name": "컨테이너 텍스트 인식을 위한 학습용 데이터셋",
      "type": "0",
      "source_file": "BOHU210001404391"
    },
    "text": [
      {
        "content": "보물섬분들도 많이 받으세여어어어어어잇...",
        "writer": "Ugw9PpHttK54q3TIenR4AaABAg.9JcBwy-MDCC9JcC9_BDo5q",
        "write_date": "2021-02-21",
        "parent_url": "https://www.youtube.com/watch?v=ekTmvPebxUg",
        "source_site": "https://www.youtube.com/"
      },
      {
        "content": "팝콘 사세요",
        "writer": "Ugw9PpHttK54q3TIenR4AaABAg.9JcBwy-MDCC9JcCILKGfD0",
        "write_date": "2021-02-21",
        "parent_url": "https://www.youtube.com/watch?v=ekTmvPebxUg",
        "source_site": "https://www.youtube.com/"
      }, ...

여기서 text 의 리스트 형태 필드만 필요하면, 위의 header는 굳이 받아올 필요가 없다.

 

위를 받아올 DTO를 만들어보면,

 

필드매핑은 @JsonProperty로 필드명을 명시해준다.

 

data class CorpusJsonDto(
    @JsonProperty("content")
    val content: String,
    @JsonProperty("write_date")
    val writeDate: String,
    @JsonProperty("url")
    val url: String,
    @JsonProperty("parent_url")
    val parentUrl: String,
    @JsonProperty("source_site")
    val sourceSite: String
)

 

계층이 복잡하면 코드레벨 명칭은 직관적으로 하고, 필드명만 매핑해 줄 수도 있다.

 

data class CorpusJsonRootDto(
    @JsonProperty("SJML")
    val rootShell: CorpusJsonMiddleShellDto
)
반응형