short

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

미침 2024. 9. 29. 20:42

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
        }
    }
    
     
  • esponse는 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}