What is the correct way to build JSON strings in Java so you don't get extra slash characters in result?

Viewed 48

I'm using Spring MVC on the back end and Bootstrap/jQuery on the front end.

My WebController's REST web service talks to a UserService, does stuff, and returns a Messages object with strings in it.

The problem is, when the JSON gets returned to the browser, it has extra \\ characters in it ...

Example:

{"readyState":4,"responseText":"{\"success\":false,\"messages\":\"{\\\"error\\\":\\\"Error modifying the user.\\\"}\"}" ...

After searching it looks like it might be nested JSON data that's causing the problem?

I'm building it like this ...

import com.fasterxml.jackson.databind.ObjectMapper;

public String toJSON() {
    String sRet = "";

    Map<String,String> messages = new HashMap<String,String>();
    messages.put("error", "Error modifying the user.");

    ObjectMapper mapper = new ObjectMapper();
    try {
        sRet = mapper.writeValueAsString(messages);
    } catch (Exception x) {
        // ...
    }

    return sRet;
}

And then returning it to the browser like this ...

@RequestMapping(value = "/json/user", method = RequestMethod.POST)
public ResponseEntity<String> modifyUser(@RequestBody String json) throws Exception {
    boolean bSuccess = true;

/* ... do the modify user stuff which builds a Messages object, and sets bSuccess = false if there's an error ... */

    JSONObject replyObj = new JSONObject();
    replyObj.put("success", bSuccess);
    replyObj.put("messages", messages.toJSON());
    return new ResponseEntity<String>(replyObj.toJSONString(), (bSuccess) ? HttpStatus.OK : HttpStatus.BAD_REQUEST);        
}

What is the correct way to build this JSONObject so it does not have all the extra slashes in it?

1 Answers

Personally I always use GSON when dealing with JSON in java.

You are right your problem has to do with nesting JSON, you add a string that contains " to messages, it escapes those because it thinks you want the literal string like that. It doesn't know that it's also a object.

Have you tried just doing this?

replyObj.put("messages", messages);
Related