I have the following JSON string that i am sending to a NodeJS server:
String string = \"{\\\"id\\\":\\\"\" + userID + \"\\\",\\\"type\\\":\\\"\" + methoden
org.json.simple.JSONObject.escape()
escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.
import org.json.simple.JSONValue;
JSONValue.escape("test string");
Add pom.xml when using maven
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<scope>test</scope>
</dependency>
public static String ecapse(String jsString) {
jsString = jsString.replace("\\", "\\\\");
jsString = jsString.replace("\"", "\\\"");
jsString = jsString.replace("\b", "\\b");
jsString = jsString.replace("\f", "\\f");
jsString = jsString.replace("\n", "\\n");
jsString = jsString.replace("\r", "\\r");
jsString = jsString.replace("\t", "\\t");
jsString = jsString.replace("/", "\\/");
return jsString;
}
The JSON specification at https://www.json.org/ is very simple by design. Escaping characters in JSON strings is not hard. This code works for me:
private String escape(String raw) {
String escaped = raw;
escaped = escaped.replace("\\", "\\\\");
escaped = escaped.replace("\"", "\\\"");
escaped = escaped.replace("\b", "\\b");
escaped = escaped.replace("\f", "\\f");
escaped = escaped.replace("\n", "\\n");
escaped = escaped.replace("\r", "\\r");
escaped = escaped.replace("\t", "\\t");
// TODO: escape other non-printing characters using uXXXX notation
return escaped;
}
If you're already using Apache commons, it provides a static method for this:
StringEscapeUtils.escapeJson("some string")
It converts any string into one that's properly escaped for inclusion in JSON
See the documentation here