Escape Character Utility for URL and JSON data – Feel free to use in your Java Project

Last updated
App Shah

Crunchify » JSON Tutorials » Escape Character Utility for URL and JSON data – Feel free to use in your Java Project

Escape Character Utility for URL and JSON data - Feel free to use in your Java Project

What is escape character in Java?

Mainly escape characters are the characters which replaces existing character with new & provided character which works best without throwing any error at runtime.

Also, it’s required in order for inter systems/process transmission, i.e. same char works for C++, Java, etc programming language.

In this tutorial we will go over two Escape Character Utilities.

  1. URLEscapeUtil
  2. JSONEscapeUtil

Also this tutorial will help you if you have below questions:

  • Java escape characters in string
  • Which characters need to be escaped on HTML
  • What does escape char means in java
  • Java escape characters in string
  • How do I escape a String for Java?
  • Escape Sequences in Java with Examples

Let’s get started:

  1. Create class
  2. Create method crunchifyURLEscapeUtil(String s) – which returns String with escape character in provided URL
  3. Create method crunchifyJSONEscapeUtil(String s) – which returns String with escape character in provided JSON
  4. In Main() –
    1. we will read the JSON data from file
    2. provide file name is Crunchify_Escape_Util.txt
  5. We use to add URL escape char

In Java when we encode a String, the following rules apply:

encode a String, the following rules - Crunchify

Here is a Crunchify_Escape_Util.txt file content. Please put it into your laptop/desktop and update path location in program.

    "founder": "App Shah",
    "blogURL": "",
    "twitter": "",
    "social": {
        "facebook": "",
        "pinterest": "”,
        "rss": ""

Option-1: Here is a complete Java Example.

  • Create our own Escape JSON and URL methods.

import java.nio.charset.StandardCharsets;
import java.text.StringCharacterIterator;

 * @author
 * Version: 1.0
 * Program: Escape Character Utility for URL and JSON data - Feel free to use in your Java Project.

public class CrunchifyEscapeCharUtility {

    public static void main(String[] args) {

        // URL Escape Utility
        String crunchifyURL = " is test";
        crunchifyLog("Sample URL: " + crunchifyURL);
        crunchifyLog("Escaped URL: " + crunchifyURLEscapeUtil(crunchifyURL));

        // JSON Escape Utility
        // We will read file first and then we will do escape char on that
        StringBuilder jsonData = new StringBuilder();
        BufferedReader crunchifyBufferReader = null;
        try {
            String crunchifyLine;
            crunchifyBufferReader = new BufferedReader(
                    new FileReader("/Users/app/Downloads/Crunchify_Escape_Util.txt"));
            while ((crunchifyLine = crunchifyBufferReader.readLine()) != null) {

            // IOException: Signals that an I/O exception of some sort has occurred.
            // This class is the general class of exceptions produced by failed or interrupted I/O operations.
        } catch (IOException exception) {
        } finally {
            try {
                if (crunchifyBufferReader != null)
            } catch (IOException ex) {

        // Let's print raw JSON file data
        crunchifyLog("\n Sample JSON: " + jsonData.toString().toString());

        // Let's print data after escaping JSON strings
        crunchifyLog("Escaped JSON: " + crunchifyJSONEscapeUtil(jsonData.toString().toString()));


    // Used to ensure that HTTP query strings are in proper form, by escaping special characters such as spaces.
    // Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme
    public static String crunchifyURLEscapeUtil(String crunchifyURL) {
        String crunchifyNewURL;

		// UTF_8: Eight-bit UCS Transformation Format.
		crunchifyNewURL = URLEncoder.encode(crunchifyURL, StandardCharsets.UTF_8);
		return crunchifyNewURL;

    // JSON Escape Utility
    public static String crunchifyJSONEscapeUtil(String crunchifyJSON) {

		// StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16 characters.
        final StringBuilder crunchifyNewJSON = new StringBuilder();

        // StringCharacterIterator class iterates over the entire String
        StringCharacterIterator crunchifyIterator = new StringCharacterIterator(crunchifyJSON);

		// current(): Implements CharacterIterator.current() for String.
        char crunchifyChar = crunchifyIterator.current();

        // DONE = \\uffff (not a character)
        while (crunchifyChar != StringCharacterIterator.DONE) {
            if (crunchifyChar == '\"') {
            } else if (crunchifyChar == '\t') {
            } else if (crunchifyChar == '\f') {
            } else if (crunchifyChar == '\n') {
            } else if (crunchifyChar == '\r') {
            } else if (crunchifyChar == '\\') {
            } else if (crunchifyChar == '/') {
            } else if (crunchifyChar == '\b') {
            } else {

                // Nothing matched - just as text as it is.
				// next(): Implements for String.
            crunchifyChar =;
        return crunchifyNewJSON.toString();

    // Simple log utility
    private static void crunchifyLog(String crunchifyData) {



Eclipse Console Output:

Sample URL: is test
Escaped URL:

 Sample JSON: {
    "founder": "App Shah",
    "blogURL": "",
    "twitter": "",
    "social": {
        "facebook": "",
        "pinterest": "”,
        "rss": ""

Escaped JSON: {\n    \"founder\": \"App Shah\",\n    \"blogURL\": \"https:\/\/\",\n    
\"twitter\": \"https:\/\/\/Crunchify\",\n    \"social\": {\n        \"facebook\": 
\"http:\/\/\/Crunchify\",\n        \"pinterest\": \"https:\/\/\/Crunchify\/crunchify-articles”,
\n        \"rss\": \"https:\/\/\/feed\/\"\n    }\n}\n

Process finished with exit code 0

Option-2: Using Apache Common’s commons-text dependency

  • Add Maven’s pom.xml dependency

Complete code:

  • Create class:

import org.apache.commons.text.StringEscapeUtils;

 * @author
 * Program: In Java How to Escape JSON? Simple Tutorial using Apache Commons Library.

public class CrunchifyEscapeJSONTutorial {

    public static void main(String[] args) {

        // StringEscapeUtils: Escapes and unescapes Strings for Java, Java Script, HTML and XML.
        // #ThreadSafe#
        // This code has been adapted from Apache Commons Lang 3.5.

        String crunchifyHTML = "{\n" +
                "    \"founder\": \"App Shah\",\n" +
                "    \"blogURL\": \"\",\n" +
                "    \"twitter\": \"\",\n" +
                "    \"social\": {\n" +
                "        \"facebook\": \"\",\n" +
                "        \"pinterest\": \"”,\n" +
                "        \"rss\": \"\"\n" +
                "    }\n" +

        // escapeJson: Escapes the characters in a String using Json String rules.
        // Escapes any values it finds into their Json String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

        // So a tab becomes the characters '\\' and 't'.
        // The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped.
        String crunchifyResult = StringEscapeUtils.escapeJson(crunchifyHTML);



    private static void crunchifyPrintUtils(String crunchifyResult) {

IntelliJ IDEA Result:

We moved over to IntelliJ IDEA since last two years. Here is a console result.

{\n    \"founder\": \"App Shah\",\n    \"blogURL\": \"https:\/\/\",\n    \"twitter\": \"https:\/\/\/Crunchify\",\n    \"social\": {\n        \"facebook\": \"http:\/\/\/Crunchify\",\n        \"pinterest\": \"https:\/\/\/Crunchify\/crunchify-articles\u201D,\n        \"rss\": \"https:\/\/\/feed\/\"\n    }\n}

Process finished with exit code 0

Let me know if you face any issue running this Java Application.

1 thought on “Escape Character Utility for URL and JSON data – Feel free to use in your Java Project”

Leave a Comment