du.study기록공간

Spring controller response when first char lowerCase and next upperCase 본문

스프링

Spring controller response when first char lowerCase and next upperCase

du.study 2021. 8. 15. 19:16
728x90

해당 블로그에도 나와있는 이슈

https://newbedev.com/why-does-jackson-2-not-recognize-the-first-capital-letter-if-the-leading-camel-case-word-is-only-a-single-letter-long

 

Programming tutorials | Newbedev

Checkout new tutorials and guides for programming languages Javascript, Python, Java, Golang, C++, PHP

newbedev.com

최근 개발을 하던 도중 조금 특이한 경우를 만났습니다.

 

간단한 예제코드

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController


@RestController
class TestController{
    @GetMapping("/test1")
    fun test1() : ResponseDto{
        return ResponseDto("test")
    }
}

class ResponseDto(val mId: String)

위와 같은경우 예상되는 response로 mId ( I가 대문자) 를 원하였지만.. 실제 결과는 다음과 같이 나왔습니다.

{
    "mid": "test"
}

 

오늘도 지식이 짧았음을 느낍니다.. 이부분을 파고들어가서 대체 왜 이렇게 동작하는지 살펴봤습니다.

 

 

BeanPropertyWriter 에서 prop name이 어떤식으로 가져와지는지를 확인해봤습니다.

 

해당부분을 보면 getMId로 앞 글자가 대문자로 치환되어있는걸 볼 수 있는데요, 실제 java로 컨버팅된 코드를 보면 ResponseDto는 다음과같이 되어있습니다.

public final class ResponseDto {
   @NotNull
   private final String mId;

   @NotNull
   public final String getMId() {
      return this.mId;
   }

   public ResponseDto(@NotNull String mId) {
      Intrinsics.checkNotNullParameter(mId, "mId");
      super();
      this.mId = mId;
   }
}

 

해결방법 :

코틀린을 사용하는 경우 다음과같이 적용하면되고 자바의 경우 getter JsonProperty를 적용하면됩니다. 

class ResponseDto(
        @get:JsonProperty("mId")
        val mId: String
)

public final class ResponseDto {
@NotNull
private final String mId;

@NotNull
public final String getMId() {
return this.mId;
}

public ResponseDto(@NotNull String mId) {
Intrinsics.checkNotNullParameter(mId, "mId");
super();
this.mId = mId;
}
}

728x90
Comments