Everyday Dev System

스프링 자바에서 json 반환 및 변환하는 방법 본문

내배캠 주요 학습/Spring 입문

스프링 자바에서 json 반환 및 변환하는 방법

chaeyoung- 2023. 6. 13. 11:08

 

1. Json 형태로 반환하기

 

1)  String으로 json 형태를 만들기

JS에 있는 타입이므로, JSON은 자바 서버에서 읽을 수 없습니다.

그리하여, 자바에서는 아래와 같이 String으로 json 형태를 만들어서 클라이언트로 반환을 해줍니다.

return "{\"name\":\"Robbie\",\"age\":95}";

package com.sparta.springmvc.response;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/response")
public class ResponseController {
    
    @GetMapping("/json/string")
    @ResponseBody
    public String helloStringJson() {
        return "{\"name\":\"Robbie\",\"age\":95}";
    }
}

 

 

2) 스프링 내부에서 자바의 클래스 형태를 JSON 형태로 변환을 해서 넘겨준다.

- 변환하고자 하는 객체에 getter 메서드가 반드시 필요

package com.sparta.springmvc.response;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/response")
public class ResponseController {

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

    @GetMapping("/json/class")
    @ResponseBody
    public Star helloClassJson() {
        return new Star("Robbie",95);
    }
}
package com.sparta.springmvc.response;

import lombok.Getter;

@Getter
public class Star {
    String name;
    int age;

    public Star(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Star() {}
}

 

 

3. Jackson 이란?

  • json 데이터 구조를 처리해주는 lib
  • 자바의 객체를 json 타입의 String으로 변환. 반대로도 가능.
  • spring 3.0.x 버전 이후로 해당 라이브러리 제공함. 그러므로 자동으로 해줌.

 

 

1) Object -> Json 변환하는 방법 (serialize 직렬화)

- 변환하고자 하는 객체에 getter 메서드가 반드시 필요

    Star star = new Star("Robbie", 95);

    ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
    String json = objectMapper.writeValueAsString(star);

    System.out.println("json = " + json);

만약, getter가 없을 경우엔 아래와 같다.

 

 

2) Json -> Object 변환하는 방법 (deserialize 역직렬화)

- 기본 생성자 & (get OR set) Method 필요

- 객체의 멤버 변수명과 키값을 일치시켜야 함.

        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());
        System.out.println("star.getAge() = " + star.getAge());