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.
JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020).
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.
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.
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