使用 nashorn 在 Java 8 中获取正确的 JSON 文字
Get a proper JSON literal in Java 8 using nashorn
我有一条要通过套接字发送的消息,一个表示 json:
的字符串
String message = "{\"sql\": \"{0}\"}";
我使用 MessageFormatter
将来自用户的实际消息放入,并将其发送到服务器。
但是,这需要是服务器能够理解的正确 JSON 字符串。
在尝试手动转义后,意识到 SQL 消息可以嵌套引号等等,我明白我想使用适当的 JSON 工具来确保字符串是 json-正确的。
我希望使用 nashorn 来保持原始代码并避免在 jar 中出现包袱。
Nashorn 似乎非常有能力并且适合这项任务,但我正在接受它,但我不确定此时该做什么。
我尝试了 中的代码:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("JSON");
message = (String) json.callMember("stringify", json.callMember("parse", message));
然而,这只是验证了我的字符串,我希望 nashorn 能够将它转义为正确的形式。
- 我知道杰克逊。
- 我知道其他 JSON 库。
如有任何见解,我们将不胜感激。
我找到的方法是通过Bindings
将用户字符串作为变量传递给引擎。
然后你可以通过engine.eval("JSON.stringify()")
进行字符串化:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Bindings bindings = engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
bindings.put("sql_from_user", sql);
String proper_json_message = (String) engine.eval("JSON.stringify({sql : sql_from_user})");
我有一条要通过套接字发送的消息,一个表示 json:
的字符串String message = "{\"sql\": \"{0}\"}";
我使用 MessageFormatter
将来自用户的实际消息放入,并将其发送到服务器。
但是,这需要是服务器能够理解的正确 JSON 字符串。
在尝试手动转义后,意识到 SQL 消息可以嵌套引号等等,我明白我想使用适当的 JSON 工具来确保字符串是 json-正确的。
我希望使用 nashorn 来保持原始代码并避免在 jar 中出现包袱。
Nashorn 似乎非常有能力并且适合这项任务,但我正在接受它,但我不确定此时该做什么。
我尝试了
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("JSON");
message = (String) json.callMember("stringify", json.callMember("parse", message));
然而,这只是验证了我的字符串,我希望 nashorn 能够将它转义为正确的形式。
- 我知道杰克逊。
- 我知道其他 JSON 库。
如有任何见解,我们将不胜感激。
我找到的方法是通过Bindings
将用户字符串作为变量传递给引擎。
然后你可以通过engine.eval("JSON.stringify()")
进行字符串化:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Bindings bindings = engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
bindings.put("sql_from_user", sql);
String proper_json_message = (String) engine.eval("JSON.stringify({sql : sql_from_user})");