Get a proper JSON literal in Java 8 using nashorn

梦想与她 提交于 2019-12-13 18:08:03

问题


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

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

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

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

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.

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

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.

I tried the code from this answer :

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

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

  • I am aware of Jackson.
  • I am aware of other JSON libraries.

Any insight would be much appreciated.


回答1:


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

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})");


来源:https://stackoverflow.com/questions/56013134/get-a-proper-json-literal-in-java-8-using-nashorn

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