JSON.simple - Escaping Special Characters


Advertisements

The following characters are reserved characters and can not be used in JSON and must be properly escaped to be used in strings.

  • Backspace to be replaced with \b

  • Form feed to be replaced with \f

  • Newline to be replaced with \n

  • Carriage return to be replaced with \r

  • Tab to be replaced with \t

  • Double quote to be replaced with \"

  • Backslash to be replaced with \\

JSONObject.escape() method can be used to escape such reserved keywords in a JSON String. Following is the example −

Example

import org.json.simple.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      String text = "Text with special character /\"\'\b\f\t\r\n.";
      System.out.println(text);
      System.out.println("After escaping.");
      text = jsonObject.escape(text);
      System.out.println(text);
   }
}

Output

Text with special character /"'
.
After escaping.
Text with special character \/\"'\b\f\t\r\n.
Advertisements