본문 바로가기

Java/Spring

@JSONSETTER 이용 중 삽질

기존 코드

@Data
@NoArgsConstructor
public class MetaData {
	...

    @JsonSetter("attributes")
    public void setCategory(List<Map> attributes) {
        Class clazz = this.getClass();

        for(Map attribute : attributes){
            String traitType = (String) attribute.get("trait_type");
            String traitValue = (String) attribute.get("value");

            try {
                Field field = clazz.getDeclaredField(traitType.toLowerCase());
                field.setAccessible(true);
                field.set(this, traitValue);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
@Data
@NoArgsConstructor
public class LandMetaData extends MetaData {
    // attributes
    private String category;
	...
}

@JsonSetter를 통해서 아래 같은 JSON을 받았을 때 attributes 를 LandMetaData로 매핑해주었다.

// JSON
{

   ...
   attributes:[

      {"trait_type":"category",

        "value":"LAND"},
      {"trait_type":"...",

        "value":"..."},

      ...

   ]

}

그런데 직렬화를 해보니 자꾸 metaData에 "category":"LAND" 가 아닌  "attributes":"LAND" 가 왔다.

attributes는 선언하지도 않았는데 말이다...

그래서 한참 삽질을 하다가 다시 보니 왠지 모르겠는데 @JsonSetter 아래의 메소드 명이 setCategory로 돼있던 것이었다... omg

그래서 LandMetadata 쪽의 setCategory가 제대로 작동하지 않던 것이었다.

 

setCategory를 다른 이름으로 바꿔주니 정상적으로 출력된다.