Programming/Spring

[Java] Jackson ObjectMapper 란?

코딩무니 2024. 1. 4. 13:00
728x90
반응형

 

ObjectMapper

자바 객체와 JSON간의 변환을 쉽게 처리할 수 있도록 도와주는 도구

 

 

ObjectMapper의 주요 개념과 특징

ObjectMapper란?

  • Jackson 라이브러리에서 제공되는 중요한 클래스 중 하나로, Java 객체를 JSON 데이터로 변환하거나 JSON 데이터를 Java 객체로 역직렬화하는 데 사용된다.
  • 자바 객체와 JSON 간의 변환을 쉽게 처리할 수 있도록 도와주는 도구
import com.fasterxml.jackson.annotation.JsonIgnore;

public class Person {
    private String name;
    private int age;

    // 생성자, getter, setter 생략
}

// age 필드를 무시하는 어노테이션
abstract class PersonIgnoreAge {
    @JsonIgnore
    abstract int getAge();
}

 

 

ObejctMapper의 특징

객체를 JSON으로 변환 (직렬화) : writeValueAsString()

  • ObjectMapper는 리플렉션을 활용해 객체로부터 Json 형태의 문자열을 만들어내는데, 이것을 직렬화(Serialize)라고 한다. 해당 부분은 @ResponseBody나 @RestController 또는 ResponseEntity 등을 사용하는 경우에 처리된다.

 

JSON을 객체로 변환 (역직렬화) : 

  • ObjectMapper는 리플렉션을 활용해 Json 문자열로부터 객체를 만들어내는데, 이것을 역직렬화(Deserialize)라고 한다. Spring에서 @RequestBody로 json 문자열을 객체로 받아올 때 역직렬화가 처리된다.
  • 역직렬화는 다음과 같은 과정을 거친다.
    1. 기본 생성자로 객체를 생성함
    2. 필드를 찾아 값을 바인딩
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToObjectExample {
    public static void main(String[] args) throws Exception {
        // ObjectMapper 인스턴스 생성
        ObjectMapper objectMapper = new ObjectMapper();

        // JSON 문자열 생성
        String jsonString = "{\"name\":\"John\",\"age\":30}";

        // JSON을 객체로 변환
        Person person = objectMapper.readValue(jsonString, Person.class);

        // 결과 출력
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

 

 

객체 매핑의 자동화

  • Java객체의 필드와 JSON의 키를 자동으로 매핑해준다. 필드명이 일치하는 경우 자동으로 변환되며, 필드명이 다르거나 특수한 매핑이 필요한 경우 어노테이션을 사용해 매핑을 직접 지정할 수 있다.
public class Person {
    @JsonProperty("full_name") // JSON의 키를 "full_name"으로 매핑
    private String name;

    private int age;

    // 생성자, getter, setter 생략
}

 

 

커스터마이징

  • ObjectMapper는 다양한 설정을 제공하여 직렬화 및 역직렬화 동작을 커스터마이징할 수 있다.
  • 예를 들어, 시간 형식, 속성 무시, Null값 처리 등을 설정할 수 있다.
ObjectMapper objectMapper = new ObjectMapper();

// Null값 무시
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

// 시간 형식 설정
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setDateFormat(new SimpleDateFormat("yyyyMMddHHmmss"));

// 속성 무시
objectMapper.addMixIn(Person.class, PersonIgnoreAge.class);
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectToJsonExample {
	public static void main(String[] args) throws Exception {
        // ObjectMapper 인스턴스 생성
        ObjectMapper objectMapper = new ObjectMapper();

        // Java 객체 생성
        Person person = new Person("John", 30);

        // 객체를 JSON 문자열로 변환
        String jsonString = objectMapper.writeValueAsString(person);

        // 결과 출력
        System.out.println(jsonString);
    }
}

 

728x90
반응형