Search code examples
jsonjava-8nashorn

Get a proper JSON literal in Java 8 using nashorn


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.


Solution

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