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.
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.
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.
You've not correctly escaped your newline, it should be:
{
"text": "This is a multiline\\n text"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With