Monday, 3 July 2017

How to Escape JSON String in Java – Eclipse IDE Tips

While working or JSON parsing in Java application it’s quite common to just copy paste a JSON String from some resources e.g. a RESTful web service and then use the Jackson library to parse the JSON. This is the quickest way to test and learn parsing JSON string in Java, but the main problem with this approach is that the JSON String also includes double quotes “” which is also used for enclosing String literals in Java. Since JSON String itself contains double quotes, when you just copy paste them in your IDE or Java source file, the didn’t work as expected. If you remember, if your String contains double quotes then those need to be escaped when you are pasting them as String literals in your Java code.

You can escape String in Java by putting a backslash in double quotes e.g.” can be escaped as\” if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quotes with escape character for even a medium size JSON is time taking, boring, and error-prone. So If you have a JSON String which you need to parse in Java using Jackson, what will you do?



How to Escape JSON String in Java Source Code using Eclipse

The quickest and the best way I found is to leverage Eclipse’s capability to Escape text when pasting into a String literal. This feature can be enabled from a setting and then Eclipse will escape all double quotes, line breaks, new lines or any other character which need escaping automatically. This can save you tons of time and can speed up your learning and testing.


1. Open Eclipse IDE

2. Go to Windows  –> Preferences –> Java –> Editor –> Typing

3. Check the checkbox “Escape text when pasting into a String literal” on section “In String literals.
Here is how your settings should look like in Eclipse IDE:


Once you did this, Eclipse will escape String if it contains any characters which need escaping. Let’s see an example now.

Suppose this is your JSON String:

"name": "John",
"email": "",
"age": 29,
"phone" : 5168161922,
"city" : "NewYork",
"hasCreditCard": false



That’s all about how to escape JSON String in Java using Eclipse IDE. This is a real time saver tip which you will appreciate every time you need to paste a JSON String into Java code. The Eclipse IDE is full of such gems and but many of us didn’t use Eclipse up to its full potential. Many programmers don’t even know essential Eclipse shortcuts and debugging tips, which can again save a lot of time while reading, writing, or troubleshooting Java code.