JSON 데이터 구조를 처리해주는 라이브러리
- Object를 JSON타입의 String으로 변환해줄 수 있다
- JSON타입의 String을 Object로 변환해줄 수 있다
스프링3.0버전 이후로는 Jackson과 관련된 API를 제공함으러써,JSON데이터를 처리하지않아도 자동으로 처리해주고 있다
- SpringBoot의starter-web에서는 default로 Jackson관련 라이브러리들을 제공
- 직접 JSON데이터를 처리해야할때 ObjectMapper를 사용
package com.sparta.springmvc;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sparta.springmvc.response.Star;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class JacksonTest {
@Test
@DisplayName("Object To JSON : get Method 필요")
void test1() throws JsonProcessingException {
Star star = new Star("Robbie", 95);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(star);
System.out.println("json = " + json);
}
@Test
@DisplayName("JSON To Object : 기본 생성자 & (get OR set) Method 필요")
void test2() throws JsonProcessingException {
String json = "{\"name\":\"Robbie\",\"age\":95}";
ObjectMapper objectMapper = new ObjectMapper();
Star star = objectMapper.readValue(json, Star.class);
System.out.println("star.getName() = " + star.getName());
System.out.println("star.getAge() = " + star.getAge());
}
}