Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

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.

Upvotes: 5

Views: 10978

Answers (2)

Rudu
Rudu

Reputation: 15892

Your above example is correct and displays correctly, however there's "human readable" \n (which would be \n in a string) and there's escaped character \n (which would be the raw \n in a string). I'm guessing whatever library you are using is generating the human readable code rather than the proper escape code.

Try: json_obj.text.replace(/\\n/g,"\n"); to convert the string back.

Upvotes: 1

Dominic Rodger
Dominic Rodger

Reputation: 99841

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

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

Upvotes: 4

Related Questions