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}
'short' 카테고리의 다른 글
| npm error EACCES: permission denied, rename (0) | 2024.12.03 |
|---|---|
| docker - no matching manifest for linux/arm64/v8 in the manifest list entries (0) | 2024.10.04 |
| MySQL Workbench, No Object selected (0) | 2024.07.19 |