JSON strings and how to handle escaped characters
I am using the official JSON library for my java pr开发者_Go百科oject 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.
You've not correctly escaped your newline, it should be:
{
"text": "This is a multiline\\n text"
}
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.
精彩评论