Skip to content

Commit

Permalink
refactor: 데이터 사이즈 1개일 때 값을 그대로 반환
Browse files Browse the repository at this point in the history
  • Loading branch information
rawfishthelgh committed Sep 26, 2023
1 parent aef4c78 commit 869cd6b
Showing 1 changed file with 10 additions and 1 deletion.
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 @@ -14,9 +15,17 @@ 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 jsonString = objectMapper.writeValueAsString(model);
String jsonString = extractJsonString(model, objectMapper);
PrintWriter printWriter = response.getWriter();
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
printWriter.write(jsonString);
}

private String extractJsonString(Map<String, ?> model, ObjectMapper objectMapper) throws JsonProcessingException {
if (model.size() == 1) {
Object value = model.values().toArray()[0];
return objectMapper.writeValueAsString(value);
}
return objectMapper.writeValueAsString(model);
}
}

0 comments on commit 869cd6b

Please sign in to comment.