views:

118

answers:

2

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.

+3  A: 

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

{
  "text": "This is a multiline\\n text"
}
Dominic Rodger
i see... The problem is that i get my json strings from a webservice and this is how they serve them. Do you know of a general way to convert a string like the one i specified to the correct format?
Savvas Dalkitsis
The escaped newline in your code is a literal backslash followed by the character n and not an escape sequence at all.
Rudu
i get what the "problem" is. I am just asking if there is an automated way of handling the string as it would be handled if it typed it as is in a java file...
Savvas Dalkitsis
+1  A: 

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.

Rudu
as i said in my question, i could replace all these cases but then i would have to handle all the special characters myself like \t. I was wondering if there was a "correct" way of handling this case.
Savvas Dalkitsis
I see a boatload of libraries supported at http://www.json.org/ which one is it you're using?
Rudu
the "official" one. the org.json one..
Savvas Dalkitsis
And the input string has proper escape codes embedded already? `org.json` supports correct escaped output, there's a mistake in here somewhere.
Rudu
actually you are right. The problem lies somewhere in the webservice... i tried loading the json from a text file and it worked. Thanks...
Savvas Dalkitsis
got it. The service would serve \\n instead of \n. I saw the output only that's why i thought what i thought :)
Savvas Dalkitsis
Glad it's sorted!
Rudu