JSON-lib escaping / saving strings

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

I just want to add a simple string that might look like JSON (but I don't want the library to automatically detect that it could be json and just treat it like a string). Looking at the source of the library, I cannot find a way to do this 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 to just have {"myString":"{\"dont\":\"treat it as json\"}"}

How to achieve this without changing the source code? I use this piece of code as a transport for chat messages from users, so it works fine for regular chat messages, but when the user enters the JSON format as a message, it will break it due to the default JSON-lib behavior described here.

+5
source share
2 answers

If I understand the question correctly, I think json-lib is unique in its assumption that the transmitted string should be parsed. Other libraries usually treat it as a String for inclusion (avoiding double quotes and backslashes if necessary), i.e. Work as you expected.

So you can consider other libraries: I would recommend Jackson , Gson also works.

+5
source

json-simple offers a JSONObject.escape() method.

+4
source

Source: https://habr.com/ru/post/889230/


All Articles