API 메시지 바디 - JSON

무삭이의 개발일지·2023년 3월 12일
0

JSON으로 데이터를 전달을 어떻게 할 수 있을까? 지금부터 알아보자

JSON 형식

  • POST : localhost:8080/request-Body-Json
  • content-type : application/json
  • message body : {"username" : "eom", "age" : 29}
    = 결과 : messageBody = {"username" : "eom", "age" : 29}

class RequestJsonServlet extends HttpServlet{
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void service(request, response) throws ServletException, IOException{
ServletInputStream inputStream= request.getInputStream();
String messageBody = StreaUtils.copyToString(inputStream, ~UTF-8);
HelloData helloData = objectMapper.readValue(MessageBody, HelloData.class);
helloData.getUsername());
helloData.getAge());
}
}

스프링 부트는 잭슨 라이브러리를 가지고 있기 때문에 ObjectMapper를 이용해서 JSON결과를 파싱해서 자바 객체로 변환한다.

응답 데이터

HTTP 응답으로 JSON을 반환할 떄는 content-type을 application/json로 지정하면 된다.
Jackson라이브러리가 제공하는 objectMapper.writeValueAsString()를 사용하면 객체를 JSON문자로 변경할 수 있다.

profile
No. Try not. Do or Do not. There is no try.

0개의 댓글