[스프링] JACKSON과 JSON

구동현·2024년 1월 17일

스프링

목록 보기
11/21

JSON 복습

@RestController 를 사용하는 경우

@Controller
public class HelloController {

    //JSON 은 자바가 해석할 수 없다. => JSON 처럼 생긴 String type 으로 반환
    @GetMapping("/json/string")
    @ResponseBody
    public String helloStringJson() {
        return "{\"name\":\"Robbie\",\"age\":95}";
    }
    // {"name" : "Robbie", "age" : 95}
    // Response Body
    // Content-Type : text/html


    // Content-Type : application/json
    // Response Body
    // { "name" : "Robbie", "age" : 95}
    @GetMapping("/json/class")
    @ResponseBody
    public Star helloStarJson() {
        return new Star("Robbie", 95);
    }
    //위의 메소드와 동일!
    // @Response Body = 우리는 html 을 반환하려는게 아니라, 그냥 객체를 반환할게
}

@RestController 사용하는 경우

  • ResponseBody 를 사용할 필요가 없음
@RestController //response body가 다 적용된다.
public class HelloController {

    @GetMapping("/json/string")
    public String helloStringJson() {
        return "{\"name\":\"Robbie\",\"age\":95}";
    }

    @GetMapping("/json/class")
    public Star helloStarJson() {
        return new Star("Robbie", 95);
    }

}

잭슨은 무엇인가


Jackson

  • JSON 데이터 구조를 처리해주는 라이브러리
  • 객체를 JSON 타입의 String으로 변환해준다.
  • JSON 타입의 String을 객체로도 변환해줄 수 있다.

구현방법

class HelloControllerTest {

    @Test
    @DisplayName("Object To JSON : get Method 필요")
    void test1() throws JsonProcessingException {
        Star star = new Star("Robbie", 95);

        ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 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}"; // JSON 타입의 String

        ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper

        Star star = objectMapper.readValue(json, Star.class);
        System.out.println("star.getName() = " + star.getName());
    }
}

객체를 JSON 으로

  • ObjectMapper objectMapper = new ObjectMapper(); : ObjectMapper 생성
  • String json = objectMapper.writeValueAsString(star); : String 으로 변환

JSON을 객체로

  • String json = "{\"name\":\"Robbie\",\"age\":95}"; : String 타입의 JSON
  • ObjectMapper objectMapper = new ObjectMapper(); : ObjectMapper 생성
  • Star star = objectMapper.readValue(json, Star.class); : 객체로 변환
profile
개발합시다

0개의 댓글