There are many posts on SO about a Spring @RestController not returning a JSON Object but instead a String. Many of these problems dealt with improper annotations on the RestController. I read them over and tried to apply the solutions where appropriate to my rest controller, but I am still returning a String to my JavaSript AJAX handler. The one thing that is different this time with this post from other SO posts regarding this issue is that my rest controller is receiving a file upload and returning a rest response. My rest controller looks like the following.
@RestController
@RequestMapping(value="/api/admin")
public class AdminImport {
@AutoWired
private SystemService systemService;
@RequestMapping(value="/import", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Map<String, Object> importData(@RequestParam("file") MultipartFile file, HttpServletRequest req, HttpServletResponse resp) throws IOException {
Boolean success = false;
try {
if(!file.isEmpty()) {
systemService.importData(file.getInputStream());
success = true;
}
} catch(Exception e) { }
Map<String, Object> map = new HashMap<>();
map.put("success",success);
return map;
}
}
My current workaround is to parse the returned String into a JSON Object using JSON.Parse.
myapi.upload = function(data, callBack) {
var options = {
url : "api/admin/import",
data : data,
processData : false,
type : "POST",
contentType : false,
mimeType : "multipart/form-data",
success : function(r) { callBack(JSON.Parse(r)); }
error : function(r) { callBack({"success":false, "msg":"Unknown error"}); }
}
$.ajax(options);
}
Any ideas on what I'm doing wrong? Is this String response something specific to uploading a file?
I have very similar logic in a different controller, but instead of accepting a file upload, it accepts a @RequestBody and the AJAX call back actually receives a JSON Object (as opposed to a String). Or is this something about the client side code?
Any help is appreciated.