[스프링] JSON 사용법

구동현·2024년 1월 17일

스프링

목록 보기
10/21

JSON

  • JSON 으로 client가 Server와 통신을 할 수 있다.

@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);
    }

}
profile
개발합시다

0개의 댓글