2

I have one spring controller which is sending JSON response to the ajax call present in my script. I have used @ResponseBody in the controller method which directly sends JSON as response when it is invoked via ajax call.

After when I added the JsonSanitizer.sanitize(myJsonString), it is returning as html in the ajax response instead of JSON. Because of that, I am unable to parse the json object now.

Example Code:

@ResponseBody
@RequestMapping(value="/getJson" method="GET")
public String fetchJsonDetails(MyObj obj) {
//DB call based on my object..
//Previously added
//return new Gson().toJson(obj);
//New line added now
return JsonSanitizer.sanitize(new Gson().toJson(obj));

}

After the above added new line, response is coming as html instead of JSON.

Please suggest me to achieve this and let me know if anything required further.

Thanks in advance.

  • How do you check that the output is html ? – NayoR May 04 '18 at 12:05
  • When I put alert for the Ajax response I am getting as html and I am not able to parse that response obj by using JSON.parse method. – Vijayaragavan V May 04 '18 at 13:02
  • It's working now. My bad I thought Json was not returned.It is returning Json but not in a correct format. I have changed that in script and now everything is working fine. Thanks @NayoR – Vijayaragavan V May 11 '18 at 17:39
  • 1
    May you post how you did solve your problem (and update it if you forgot to add some information to it) ? May help someone else ;) – NayoR May 14 '18 at 14:11
  • Actually in the returned format, I have checked the values. It has some additional encoded values when I use enocde.forjavascript in server side. I just replaced encoded values in the script and it is converted back to valid Json. And then I have passed it using JSON.parse method and accessed all those values. – Vijayaragavan V May 15 '18 at 03:27

1 Answers1

1

You may specify the kind of return you do:

@ResponseBody
@GetMapping(value="/getJson", produces="application/json")
public String fetchJsonDetails(MyObj obj) {
    // DB Call
    return JsonSanitizer.sanitize(new Gson().toJson(obj));
}

You can also use

import org.springframework.http.MediaType;
...
@GetMapping(value="/getJson", produces=MediaType.APPLICATION_JSON_VALUE)
NayoR
  • 702
  • 6
  • 13