Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

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 CrunchifyEscapeCharUtility.java
  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 java.net.URLEncoder 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": "https://crunchify.com",
    "twitter": "https://twitter.com/Crunchify",
    "social": {
        "facebook": "http://facebook.com/Crunchify",
        "pinterest": "https://www.pinterest.com/Crunchify/crunchify-articles”,
        "rss": "https://crunchify.com/feed/"
    }
}

Here is a complete Java Example

package crunchify.com.tutorial;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.StringCharacterIterator;

/**
 * @author Crunchify.com 
 * Version: 1.0 
 * Updated: 01.25.2016
 * 
 */

public class CrunchifyEscapeCharUtility {

        public static void main(String[] args) {

                // URL Escape Utility
                String crunchifyURL = "https://crunchify.com/this 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
                String jsonData = "";
                BufferedReader br = null;
                try {
                        String line;
                        br = new BufferedReader(
                                        new FileReader("/Users/<Username>/Documents/Crunchify_Escape_Util.txt"));
                        while ((line = br.readLine()) != null) {
                                jsonData += line + "\n";
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                if (br != null)
                                        br.close();
                        } catch (IOException ex) {
                                ex.printStackTrace();
                        }
                }

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

                // Let's print data after escaping JSON strings
                crunchifyLog("Escaped JSON: " + crunchifyJSONEscapeUtil(jsonData.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 = null;
                try {
                        crunchifyNewURL = URLEncoder.encode(crunchifyURL, "UTF-8");
                } catch (UnsupportedEncodingException ex) {
                        throw new RuntimeException("UTF-8 not supported", ex);
                }
                return crunchifyNewURL;
        }

        // JSON Escape Utility
        public static String crunchifyJSONEscapeUtil(String crunchifyJSON) {
                final StringBuilder crunchifyNewJSON = new StringBuilder();

                // StringCharacterIterator class iterates over the entire String
                StringCharacterIterator iterator = new StringCharacterIterator(crunchifyJSON);
                char myChar = iterator.current();

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

                                // nothing matched - just as text as it is.
                                crunchifyNewJSON.append(myChar);
                        }
                        myChar = iterator.next();
                }
                return crunchifyNewJSON.toString();
        }

        // Simple log utility
        private static void crunchifyLog(String crunchifyData) {
                System.out.println(crunchifyData);
        }

}

Eclipse Console Output:

Sample URL: https://crunchify.com/this is test
Escaped URL: http%3A%2F%2Fcrunchify.com%2Fthis+is+test

 Sample JSON: {
    "founder": "App Shah",
    "blogURL": "https://crunchify.com",
    "twitter": "https://twitter.com/Crunchify",
    "social": {
        "facebook": "http://facebook.com/Crunchify",
        "pinterest": "https://www.pinterest.com/Crunchify/crunchify-articles”,
        "rss": "https://crunchify.com/feed/"
    }
}

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

The post Escape Character Utility for URL and JSON data – Feel free to use in your Java Project appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires