Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON strings and how to handle escaped characters

I am using the official JSON library for my java project ad i have noticed something weird.

If i have a json such as this:

{
  "text": "This is a multiline\n text"
}

And i try to get the string like this:

System.out.println(jsonObject.getString("text"));

I get this on the output:

This is a multiline\n text

Instead of :

This is a multiline
text

Anyone know of the correct way to handle the special characters such as \n and \t? I could always replace each one but I would have to handle all of them one by one.

like image 302
Savvas Dalkitsis Avatar asked Sep 07 '10 13:09

Savvas Dalkitsis


People also ask

How do I ignore an escape character in a string?

An escape sequence is a set of characters used in string literals that have a special meaning, such as a new line, a new page, or a tab. For example, the escape sequence \n represents a new line character. To ignore an escape sequence in your search, prepend a backslash character to the escape sequence.

How do you escape the special characters in a JSON string in Java?

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 quote with an escape character for even a medium-size JSON is time taking, boring, and error-prone.


1 Answers

You've not correctly escaped your newline, it should be:

{
  "text": "This is a multiline\\n text"
}
like image 187
Dominic Rodger Avatar answered Sep 22 '22 21:09

Dominic Rodger