Spring

Jackson ObjectMapper 사용하기

구티맨 2022. 4. 25. 15:08

Jackson objectmapper는 Java 오브젝트와 JSON 간에 직렬화, 역직렬화를 해주는 역할을 합니다.

 

Jackson 사용을 위해 의존성을 추가합니다.

databind는 jackson-annotations, jackson-core 의존성도 포함되어 있습니다.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.2.2</version>
</dependency>

Cat 클래스를 이용하여 직렬화, 역직렬화를 해보겠습니다.

@Getter
@Setter
@NoArgsConstructor
public class Cat {
    private String name;

    public Cat(String name) {
        this.name = name;
    }
}

Object to Json

ObjectMapper objectMapper = new ObjectMapper();

Cat cat = new Cat("kitty");
String catString = objectMapper.writeValueAsString(cat);
System.out.println("catString : " + catString);

--- output ---
catString : {"name":"kitty"}

Json to Object

String json = "{\"name\":\"kitty\"}";
Cat cat2 = objectMapper.readValue(json, Cat.class);
System.out.println("cat2 name :  " + cat2.getName());

--- output ---
cat2 name :  kitty

Json to Jackson JsonNode

JsonNode jsonNode = objectMapper.readTree(json);
String name = jsonNode.get("name").asText();
System.out.println("Tree cat2 name : " + name);

--- output ---
Tree cat2 name : kitty

Json List to List

String jsonList = "[{\"name\":\"kitty\"},{\"name\":\"kitty2\"}]";
List<Cat> cats = objectMapper.readValue(jsonList, new TypeReference<List<Cat>>() {});
for (Cat catElement : cats) {
    System.out.println("catElement : " + catElement.getName());
}

--- output ---
catElement : kitty
catElement : kitty2