error

[ajax] Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON

dddzr 2023. 9. 26. 11:16

서버 측 에러

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Class `com.deom.model.FileData` not subtype of `java.util.Map<java.lang.String,java.lang.String>`; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Class `com.deom .model.FileData` not subtype of `java.util.Map<java.lang.String,java.lang.String>` (through reference chain: java.util.HashMap["fileList"]->java.util.ArrayList[0])]

 

클라이언트 측 에러

Could not write JSON: Class `com.dome.model.FileData` not subtype of `java.util.Map<java.lang.String,java.lang.String>

 

수정 방법

HashMap<String, List<Map<String, String>>>로 받아 온 값을 ajax에서 JSON으로 파싱하지 못한다는 에러같아서

controller의 리턴타입을 HashMap<String, String>으로 수정하고 ajax에서 parse하도록 수정하였습니다.

 

서버 측 기존 코드

  @RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "multipart/form-data")
  @ResponseBody
  public HashMap<String, List<Map<String, String>>> Test(@RequestParam Map<String, String> params, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
	List<Map<String, String>> fileList = fileService.getFileList(params);
    HashMap<String, List<Map<String, String>>> result = new HashMap<String, List<Map<String, String>>>();
    result.put("fileList", fileList);
    return result;

  }

 

서버 측  수정 코드

  @RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "multipart/form-data")
  @ResponseBody
  public HashMap<String, String> Test(@RequestParam Map<String, String> params, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<Map<String, String>> fileList = fileService.getFileList(params);
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(fileList);
    System.out.println(json);
    HashMap<String, String> result = new HashMap<String, String>();
    result.put("fileList", json);
    return result;
  }

 

클라이언트 측 수정 코드

var formData = new FormData();
formData.append(
"fileId",
$("#" + formId)
  .find("input[type=hidden]")
  .val()
);
$.ajax({
  url: commonUtil.getDataServiceURL("test"),
  type: "POST",
  data: formData,
  dataType: "json",
  contentType: false,
  processData: false,
  async: false,
  success: function (data) {
      var list = JSON.parse(data.fileList); //data.fileList;
      if (list.length > 0) {
        //code
      }
  },
  error: function (xhr, status, error) {
    console.error("Ajax Error:" + xhr.responseText);
  },
});