Spring

ObjectMapper

테니드2 2025. 3. 18. 23:00
package com.example.obejctmapper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ObjectMapperApplicationTests {

    @Test
    void contextLoads() throws JsonProcessingException {
        System.out.println("--------------");

        // Text JSON -> Object
        // Object -> Text JSON

        // controller req json(text) -> object
        // response object -> json(text)


        var objectMapper = new ObjectMapper();

        // object -> text
        // object mapper get 메소드를 활용
        var user = new User("jun",20,"010-1111-2222");
        var text = objectMapper.writeValueAsString(user);
        System.out.println(text);

        // text -> object
        // object mapper 는 디폴트 생성자를 필요로 한다.
        var objectUser = objectMapper.readValue(text, User.class);
        System.out.println(objectUser);
    }

}

objectMapper는 object 타입을 text로 변환할 때 get메소드를 활용한다. 멤버 변수의 get메소드 이외에 get-으로 시작하는 메소드가 있다면 변환 과정에서 에러가 발생할 수 있으니 주의하자.

 

text를 object로 변환 할때는 디폴트 생성자가 반드시 있어야 동작한다.

 

 

package com.example;

import com.example.dto.Car;
import com.example.dto.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        User user = new User();
        user.setName("홍길동");
        user.setAge(10);


        Car car1 = new Car();
        car1.setName("K5");
        car1.setCarNumber("11가 1111");
        car1.setType("sedan");

        Car car2 = new Car();
        car2.setName("Q5");
        car2.setCarNumber("22가 2222");
        car2.setType("SUV");


        List<Car> carList = Arrays.asList(car1, car2);
        user.setCars(carList);

        System.out.println(user);

        String json = objectMapper.writeValueAsString(user);
        System.out.println(json);


        JsonNode jsonNode = objectMapper.readTree(json);
        String _name = jsonNode.get("name").asText();
        int _age = jsonNode.get("age").asInt();
        System.out.println("name : " + _name);
        System.out.println("age : " + _age);


        JsonNode cars = jsonNode.get("cars");
        ArrayNode arrayNode = (ArrayNode) cars;
        List<Car> _cars = objectMapper.convertValue(arrayNode, new TypeReference<List<Car>>() {});
        System.out.println(_cars);

        ObjectNode objectNode = (ObjectNode) jsonNode;
        objectNode.put("name","jun");
        objectNode.put("age",20);

        System.out.println(objectNode.toPrettyString());


    }
}

ObjectMapper의 readTree 메소드를 통해 문자열 형태의 JSON 데이터를 JsonNode로 변경할 수 있다. JsonNode에서 get 메소드를 통해 값을 추출할 수 있지만, Array 타입과 같은 경우에는 새로운 노드로 취급하므로 바로 사용이 불가하다. 따라서 다시 JsonNode로 추출하여 형변환 한 후 convertValue로 원하는 클래스 타입으로 변경한다.

JsonNode는 내부적으로 값을 변경할 수 없지만 ObjectNode로 형변환 후 put 메소드를 활용하면 값을 업데이트 하는 방식으로 수정이 가능하다.

 

이러한 방식을 잘 활용하기 위하면 JSON 표준 스펙을 잘 정의하고 사전에 미리 인지하고 있어야 한다.