티스토리 뷰

Jackson 직렬화 관련 주요 어노테이션 

annotation Description
*@JsonIgnore
@JsonIgnoreProperties
@JsonIgnoreType
해당 필드는 무시.
deserialize / serialize에서 제외 
*@JsonProperty json 필드명과 객체의 속성명이 다를 때 사용하며 해당 속성에는 read only, write only 등이 있다. 
@JsonSetter
@JsonGetter
특정 필드의 setter/getter를 대체할 때 사용 
@JsonPropertyOrder 직렬화 순서 지정 
@JsonRawValue json 형태의 문자열인 value를 문자가 아닌 json으로 변환한다. 
@JsonValue 직렬화에 사용할 단일 메소드
이 메소드의 반환 값으로 직렬화된다. 
@JsonRootName root를 지정할 때 사용. 
@JsonSerialize
@JsonDeserialize
객체를 마샬링할 때 serializer/deserializer 지정 
@JsonCreator 역직렬화시 필드명을 달리 하거나 일부 필드를 제외할 때 사용. 
@JsonAlias 속성에 하나 이상의 매핑할 때 사용 
@JsonInclude null 또는 기본값 속성을 제외시킬 때 사용 

샘플 코드 

@Slf4j
@RestController
@RequestMapping("/controller/response/json")
public class ResponseJsonAPIController {

    /**
     * jackson annotation 테스트    
     * @return
     */
    @PostMapping()
    public ResponseEntity<JsonTest> jsonTest(@RequestBody final JsonTest body) {
        log.debug("requestParamRequiredFalse call : "+body);
        return ResponseEntity.ok(body);
    }

    @Getter
    @Setter
    @ToString
    //@JsonRootName(value="user") // SerializationFeature.WRAP_ROOT_VALUE, DeserializationFeature.UNWRAP_ROOT_VALUE enable 필요 
    @JsonPropertyOrder({ "userId", "name" , "created" }) // 순서 정의 
    @JsonInclude(Include.NON_NULL) // 값이 null 이 아닌 것만 포함한다. 
    public static class JsonTest {

        /**
         * testId라는 필드명 사용. 
         */
        @JsonProperty(value="testId")
        private String id;

        /**
         * 값을 받지만 serialize는 하지 않는다. 
         */
        @JsonProperty(access=JsonProperty.Access.WRITE_ONLY)
        private String name;
        
        /**
         * 이 필드는 제외 
         */
        @JsonIgnore
        private Boolean test;
        
        private String emptyField;

        /**
         * yyyy-MM-dd 포맷으로 매핑. 
         */
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone="Asia/Seoul")
        private Date created;

        public JsonTest() {
            super();
        }

        public JsonTest(String id, String name, Boolean test, Date created) {
            super();
            this.id = id;
            this.name = name;
            this.test = test;
            this.created = created;
        }

        /**
         * "userId"라는 이름으로 받아서 id에 값을 넣는다. 
         * @param id
         * @param name
         */
        @JsonCreator
        public JsonTest(@JsonProperty("userId") String id,@JsonProperty("name") String name) {
            super();
            this.id = id;
            this.name = name;
        }
    }

}

테스트 

@WebMvcTest(controllers = ResponseJsonAPIController.class)
class ResponseJsonAPIControllerTest {

    @Autowired 
    private MockMvc mockMvc;
 
    private JsonTest getJsonTest() {
        return new JsonTest("test", "테스트", true, DateUtil.parseDate("2022-05-12"));
    }

    @Test
    void dateMapping() throws Exception {
        JsonTest params = getJsonTest();
        ObjectMapper objectMapper = new ObjectMapper();
        String body = objectMapper.writeValueAsString(params);
        mockMvc.perform(MockMvcRequestBuilders.post("/controller/response/json")
                .contentType(MediaType.APPLICATION_JSON)
                .content(body))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.testId").value(params.getId()))
                .andExpect(jsonPath("$.created").value(DateUtil.formatDate(params.getCreated())))
                ;
    }

}

 

Git : https://github.com/kkaok/study-springboot/blob/main/src/main/java/eblo/study/springboot/controller/ResponseJsonAPIController.java

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함