티스토리 뷰

728x90

 

myBatis를 사용하거나 @ReqeustBody 어노테이션을 사용하면 수신되는 JSON 데이터를 찰떡같이 맵핑해준다.

하지만 필드명 시작이 대문자이면 주의해주어야한다.

원인은 Jackson은 Java Bean 네이밍 규칙으로 Java 클래스의 Json property를 맵핑하기 때문이다.

 

Java Bean 네이밍 규칙 핵심은 이렇다. (JavaBeans Spec https://www.oracle.com/java/technologies/javase/javabeans-spec.html)

1. 시작은 일반적으로 소문자이다.

2. 처음 두문자가 대문자이면 그대로 사용한다.

 

8.8 Capitalization of inferred names.
Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case. However to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone. So for example, 

“FooBah” becomes “fooBah” 
“Z” becomes “z” 
“URL” becomes “URL” 

We provide a method Introspector.decapitalize which implements this conversion rule.
Here’s the source code for Introspector.decapitalize(). 

public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}

The following table shows how the 1st two characters map. If this was a mathematical function, I’d say it wasn’t one-to-one. (‘aa’ and ‘Aa’ imply the same getter)

property 	getter 
aa	getaa()
aA	getaA()
Aa	getaa()
AA	getAA()

해결 방안은 @JsonSetter 어노테이션으로 property 이름을 명시해준다.

예시

Client에서 생성한 데이터
Server에서 수신한 데이터
{"Name": "GilDong"}
{"name": "GilDong"}

 

Client

public class Data {
    @JsonProperty
    private String Name;
}
 

Server

public @ResponseBody JsonNode getData (@RequestBody data) {
    ....
}
 
public class Data {
    private String Name;

    ....
    @JsonSetter("Name")
    public String getName() {
        return this.Name;
    }
}
 

 

 

728x90

'Spring' 카테고리의 다른 글

@EnableKafkaStreams 분석 - 어떻게 streams는 start 되는가?  (1) 2022.05.17
Kafka Streams - Spring boot example  (0) 2022.05.17
Filter, Interceptor, AOP  (0) 2022.04.13
JSON Jackson Annotaion으로 처리  (0) 2022.04.02
Json 맵핑 원리  (0) 2022.04.02
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31