JSON-lib转义/保留字符串 [英] JSON-lib escaping / preserving strings

查看:245
本文介绍了JSON-lib转义/保留字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON-lib库进行java http://json-lib.sourceforge.net

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

我只想添加一个看起来像JSON的简单字符串(但我不希望库自动弄清楚它可能是json而只是把它当作字符串对待)。看看图书馆的来源我找不到没有丑陋黑客的方法。

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.

例子:

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

object.toString()会给我们 {myString:{dont:将其视为json}}

我想要的只是要 {myString:{\dont\:\将其视为json \}}

如何在不修改源代码的情况下实现它?我正在使用这段代码作为来自用户的聊天消息的传输 - 所以它适用于正常的聊天消息,但是当用户将输入JSON格式作为消息时,由于此处描述的JSON-lib的默认行为,它将破坏它。

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-lib在假设传递的String需要被解析时是独一无二的。其他lib通常将其视为要包含的String(必要时转义双引号和反斜杠),即按预期工作。

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.

所以你可能要考虑其他图书馆:我建议 Jackson ,Gson也可以。

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

这篇关于JSON-lib转义/保留字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆