使用nashorn在Java 8中获取正确的JSON文字 [英] Get a proper JSON literal in Java 8 using nashorn

查看:450
本文介绍了使用nashorn在Java 8中获取正确的JSON文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条消息要通过套接字发送,它是代表json的字符串:

I have a message that's to be sent over a socket, a string that represents a json:

String message = "{\"sql\": \"{0}\"}";

我使用MessageFormatter来输入来自用户的实际消息,并将其发送到服务器.

I use MessageFormatter to put in the actual message from the user, and send it to the server.

但是,这必须是服务器可以理解的正确JSON字符串.

However, this needs to be a proper JSON string for the server to understand.

在尝试了手动转义之后,意识到SQL消息可以包含嵌套的引号和其他内容,我知道我想使用适当的JSON工具来确保字符串是JSON正确的.

After dabbling with manual escaping, realizing the SQL message can have nested quotes and whatnot, I understand I want to use a proper JSON tool to make sure the string is json-correct.

我希望使用nashorn保持代码的香草味,并避免在罐子里放行李.

I wish to use nashorn to keep the code vanilla and avoid baggage in the jar.

纳斯霍恩(Nashorn)似乎很胜任并且很适合完成这项任务,但是我正在随手拿起它,现在还不确定该怎么做.

Nashorn seems quite capable and fit for the task, but I'm picking it up as I go, and I'm not sure what to do at this point.

我尝试了此答案中的代码:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("JSON");
message = (String) json.callMember("stringify", json.callMember("parse", message));

但是,这只是验证我的字符串,我希望nashorn实际将其转义为正确的形式.

However, this merely validates my string, I wish nashorn to actually escape it to a proper form.

  • 我知道杰克逊.
  • 我知道其他JSON库.

任何见识将不胜感激.

推荐答案

我发现的方法是通过Bindings将用户字符串作为变量传递给引擎.

The way I found is to pass the user string as a variable to the engine via Bindings.

然后您可以通过engine.eval("JSON.stringify()")进行字符串化:

Then you can stringify via 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})");

这篇关于使用nashorn在Java 8中获取正确的JSON文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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