basic/Java
SpringBoot에서 JSON으로 데이터 보내는 방법 3가지 REST통신하기
ekgoddldi
2021. 9. 30. 20:56
방법1. @RequestBody와 @ResponseBody를 이용하여 HTTP통신(JSON형식)을 하는것이다.
@Controller
public class TestController {
@ResponseBody
@RequestMapping("/restful")
public RestfulSpring test(){
RestfulSpring rs = new RestfulSpring();
rs.setType("JSON");
return rs;
}
}
|

방법2. 컨트롤러로 JSON객체를 전송하는 가장 쉬운방법으로 @RestController를 사용하면 된다. (@RestController는 @Controller와 @ResponseBody가 합쳐진것이라 보면된다.)
@RestController
public class HelloController {
@GetMapping("/hello/dto")
public HelloResponseDto helloDto(@RequestParam("name") String name, @RequestParam("amount") int amount){
return new HelloResponseDto(name, amount);
}
}
|
하지만 몇몇의 경우 부득이하게 직접 JSON객체를 만들어서 보내야되는 경우가 있다. 그럴 경우에 사용하는 방법이다.
방법3. 직접 JSON객체 만들어보내기(구글의 GSON 또는 org.codehaus.jettison.json.JSONObject이용하기)
GSON의 경우 의존성을 추가해야한다.
메이븐 저장소 https://mvnreository.com/artifact/com.google.code.gson/gson
GSON 깃허브 https://github.com/google/gson