rhakdnj / kopring

0 stars 0 forks source link

직렬화 #24

Open rhakdnj opened 7 months ago

rhakdnj commented 7 months ago

직렬화는 객체를 스트림으로 전환하는 과정입니다.

구체적으로 pojo(plain old java object)를 JSON, XML롤 전환하는 작업을 직렬화라고 합니다.

자바의 JSON 직렬화 프레임워크는 Jackson입니다.

@JsonProperty(name="user_name")

이는 Customize field names in reponse 중에 하나입니다.

rhakdnj commented 7 months ago

Return only selected fields

Filtering : i.g. Filter out Passwords

import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class FilterController {
  @GetMapping("/filter")
  fun filter(): SomeBean {
    return SomeBean()
  }

//   @JsonIgnoreProperties("field2", "field3")
  data class SomeBean(
    val field1: String = "field1",
    @JsonIgnore
    val field2: String = "field2",
    val field3: String = "field3",
  )
}
import com.fasterxml.jackson.annotation.JsonFilter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider
import org.springframework.http.converter.json.MappingJacksonValue
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class FilterController {
  @GetMapping("/filter")
  fun filter(): MappingJacksonValue {
    val someBean = SomeBean()
    val mappingJacksonValue = MappingJacksonValue(someBean)
    mappingJacksonValue.filters = SimpleFilterProvider().addFilter(
      "SomeBeanFilter",
      SimpleBeanPropertyFilter.filterOutAllExcept("field1", "field3")
    )
    return mappingJacksonValue
  }

  @JsonFilter("SomeBeanFilter")
  data class SomeBean(
    val field1: String = "field1",
    @JsonIgnore
    val field2: String = "field2",
    val field3: String = "field3",
  )
}