How to remove escape characters when JSON is added to model in spring rest controller

Anand Sai Krishna picture Anand Sai Krishna · Oct 14, 2015 · Viewed 14.7k times · Source

I am fetching JSON stored in DB (JSON is stored as a string in DB) and adding it to the model object in the controller.

@RequestMapping( method = RequestMethod.GET, value = "/all" )
public void getJson(HttpServletRequest httpServletRequest, Model model){

    String json = serviceDao.getResponseJson(); 
    System.out.println(json); //Output: {"Response":[{"Id":"1","Name":"GAD"},{"Id":"2","Name":"GBD"}],"Status":"Success"}
    model.addAttribute("result",json);
}

But when I invoke the service from a browser, escape characters are added the response.

http://localhost:8080/MyApplication/all.json

{"result":"{\"Response\":[{\"Id\":\"1\",\"Name\":\"GAD\"},{\"Id\":\"2\",\"Name\":\"GBD\"}],\"Status\":\"Success\"}"}

Can you please help me on the way to send the JSON object to the client in a webservice without escape characters.

Answer

Angelo Angeles picture Angelo Angeles · Oct 14, 2015

Instead of adding the string to model return JSON directly

@RequestMapping(value="/all")
public @ResponseBody String getJson(){
   //Logic
    return json; 
}