Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON-lib escaping / preserving strings

I am using JSON-lib library for java http://json-lib.sourceforge.net

I just want to add simple string which can look like JSON (but i do not want library to automatically figure out that it might be json and just to treat it as string). Looking into source of library I can't find the way to do it without ugly hacks.

example:

JSONObject object = new JSONObject();
String chatMessageFromUser = "{\"dont\":\"treat it as json\"}";
object.put("myString", chatMessageFromUser);

object.toString() will give us {"myString":{"dont":"treat it as json"}}

and i want just to have {"myString":"{\"dont\":\"treat it as json\"}"}

How to achieve it without modifying source code ? I am using this piece of code as transport for chat messages from users - so it works OK for normal chat messages, but when user will enter JSON format as message it will break it because of default behavior of JSON-lib described here.

like image 899
Mike Pandorium Avatar asked Dec 28 '10 15:12

Mike Pandorium


People also ask

Does JSON need to be escaped?

JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020).

How do I add an escape character to 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

If I understand question correctly, I think json-lib is unique in its assumption of a String being passed needing to be parsed. Other libs typically treat it as String to include (with escaping of double-quotes and backslashes as necessary), i.e. work as you would expect.

So you may want to consider other libraries: I would recommend Jackson, Gson also works.

like image 158
StaxMan Avatar answered Nov 02 '22 00:11

StaxMan