diff --git a/app/src/main/java/com/techcourse/controller/UserController.java b/app/src/main/java/com/techcourse/controller/UserController.java index 8edea242f0..0c57470009 100644 --- a/app/src/main/java/com/techcourse/controller/UserController.java +++ b/app/src/main/java/com/techcourse/controller/UserController.java @@ -29,4 +29,4 @@ public ModelAndView show(HttpServletRequest request, HttpServletResponse respons modelAndView.addObject("user", user); return modelAndView; } -} \ No newline at end of file +} diff --git a/mvc/src/main/java/webmvc/org/springframework/web/servlet/view/JsonView.java b/mvc/src/main/java/webmvc/org/springframework/web/servlet/view/JsonView.java index dc1ef9bf87..b946c0a1bf 100644 --- a/mvc/src/main/java/webmvc/org/springframework/web/servlet/view/JsonView.java +++ b/mvc/src/main/java/webmvc/org/springframework/web/servlet/view/JsonView.java @@ -1,5 +1,6 @@ package webmvc.org.springframework.web.servlet.view; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -11,16 +12,21 @@ public class JsonView implements View { @Override public void render(final Map model, final HttpServletRequest request, HttpServletResponse response) throws Exception { - ObjectMapper objectMapper = new ObjectMapper(); + String body = createJsonBody(model); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().write(body); + } + + private String createJsonBody(final Map model) throws JsonProcessingException { + final ObjectMapper objectMapper = new ObjectMapper(); String json = ""; if (model.size() == 1) { json = objectMapper.writeValueAsString(model.get(model.keySet().iterator().next())); } else { json = objectMapper.writeValueAsString(model); } - response.setContentType("application/json"); - response.setCharacterEncoding("utf-8"); - response.getWriter().write(json); + return json; } @Override