Skip to content

Commit

Permalink
refactor: Json Body 생성 부분 메서드 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
echo724 committed Sep 28, 2023
1 parent 7bd858e commit a423a95
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ public ModelAndView show(HttpServletRequest request, HttpServletResponse respons
modelAndView.addObject("user", user);
return modelAndView;
}
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -11,16 +12,21 @@ public class JsonView implements View {

@Override
public void render(final Map<String, ?> 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<String, ?> 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
Expand Down

0 comments on commit a423a95

Please sign in to comment.