JSON-lib escaping / preserving strings

心不动则不痛 提交于 2019-12-09 12:56:14

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4547143/json-lib-escaping-preserving-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!