Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 366
Anand Sai Krishna Avatar asked Oct 14 '15 05:10

Anand Sai Krishna


People also ask

How remove all escape characters from JSON string?

String jsonFormattedString = jsonStr. replaceAll("\\", "");

How remove slashes from JSON in Java?

Replace slash everywhere in the string----------->str =str. replace(/\//g,""); You can convert back to JSON object again using-->var output =JSON. parse(str);


1 Answers

Instead of adding the string to model return JSON directly

@RequestMapping(value="/all")
public @ResponseBody String getJson(){
   //Logic
    return json; 
}
like image 99
Angelo Angeles Avatar answered Oct 06 '22 05:10

Angelo Angeles