Anand Sai Krishna
Anand Sai Krishna

Reputation: 319

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.

Upvotes: 9

Views: 19014

Answers (4)

Nassa44
Nassa44

Reputation: 316

It will work definitely.

 String str = "result':'\'\'Respon'";
 String result = str.replaceAll("\\\'", ""); 
 Log.e("Result",result);

Upvotes: 0

Angelo Angeles
Angelo Angeles

Reputation: 991

Instead of adding the string to model return JSON directly

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

Upvotes: 4

Naman Gala
Naman Gala

Reputation: 4692

If you are using spring, you can use @ResponseBody and directly return your class object instead of String.

You can refer example given in this link.

Also don't forget to include maven dependency.

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>

Upvotes: 0

You can use replaceAll:

String json = serviceDao.getResponseJson();

if (json != null && !json.isEmpty()) {
    model.addAttribute("result", json.replaceAll("\\\\", ""));
}

Upvotes: -1

Related Questions