본문 바로가기
Etc

직렬화와 역직렬화(Jackson 라이브러리)

by SuperDT 2024. 9. 29.

Jackson 라이브러리 (springboot는 기본 자동설정, ObjectMapper 핵심 클래스)

  • request는 Json → DTO: Deserialization 역직렬화 (readValue)
    • dto 객체의 set메소드 네이밍을 따라서 역직렬화 진행
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class JacksonLib {
        public static void main(String[] args) throws Exception {
            ObjectMapper mapper = new ObjectMapper();
    
            // JSON 문자열
            String jsonString = "{\\"firstName\\":\\"bear\\",\\"lastName\\":\\"ab\\",\\"age\\":30}";
    
            // JSON 문자열을 Java 객체로 변환
            User user = mapper.readValue(jsonString, User.class);
            System.out.println(user.getFirstName());  // 출력: bear
        }
    }
    
  • response는 DTO → Json: Serialization 직렬화 (writeValueAsString)
    • dto 객체의 get메소드 네이밍을 따라서 직렬화 진행
    • 반환하는 응답의 키 이름을 변경하고 싶으면 변수에 @JsonProperty(”keyName”) 붙이거나 get을 재정의
    • 반환하고 싶지 않은 데이터에 대해서는 @JsonIgnore 붙이기
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class JacksonLib {
        public static void main(String[] args) throws Exception {
            ObjectMapper mapper = new ObjectMapper();
    
            // Java 객체 생성
            User user = new User("bear", "ab", 30);
    
            // Java 객체를 JSON 문자열로 변환
            String jsonString = mapper.writeValueAsString(user);
            System.out.println(jsonString);
        }
    }
    //{"firstName":"bear","lastName":"ab","age":30}
    

 

'Etc' 카테고리의 다른 글

Vertica에 대해서  (1) 2024.10.06
데이터 웨어하우스(DW) 란  (0) 2024.09.29
영속성 컨텍스트 란  (1) 2024.09.22
Int와 Integer 확인 사항  (0) 2024.09.22
Broken pipe 오류  (1) 2024.09.08