In JDK 8, is there any planned interoperability between Nashorn and the new JSON-P (javax.json) API?

StackOverflow https://stackoverflow.com/questions/19060036

  •  29-06-2022
  •  | 
  •  

Question

Recently I've taken a look at both Nashorn and the new JSON-P API (javax.json). Since both are obviously geared towards JSON, is there any planned interoperability between them (ie. will Nashorn include native support for javax.json.spi.JsonObject)?

Edit #1

@Vik Gamov,

By interoperability, I mean a way to inject javascript / JSON objects into the script at runtime. I know Nashorn allows for objects from other JVM languages, like standard Java objects. However, if someone wanted to use 100% javascript there needs to be a simple way to create pure JS objects from the outside and it seems like jlaskey, hannesw (as per comments on JSObject) and the other guys/gals at Oracle have provided a way to make that happen.

As it turns out, they have also provided a default implementation for JSObject with ScriptObjectMirror.

Was it helpful?

Solution

After digging into the Nashorn code, I did not find any references to the javax.json packages. However, I did find the following comment in JSObject:

This class can also be subclassed by an arbitrary Java class. Nashorn will treat objects of such classes just like nashorn script objects. Usual nashorn operations like obj[i], obj.foo, obj.func(), delete obj.foo will be glued to appropriate method call of this class.

It would be fairly easy to wrap JsonObject and JsonArray in a JSObject implementation.

Edit #1

As it turns out the ScriptObjectMirror class can be used as a go-by or as a default implementation of JSObject itself.

OTHER TIPS

You can get access to any Java class in Javascript with nashorn and JSR-223 apis. For example, here is you can use Jackson or google gson mappers in javascript code.

var json = {};

// google gson mapper
var MAPPER = new com.google.gson.Gson();

/**
 * Converts object to a json string.
 * @param object - the object to convert.
 * @return {String} the resultant json.
 */
json.toJson = function (object) {
    return MAPPER.toJson(object);
};


json.roundtripJson = function (object) {
    return JSON.parse(json.toJson(object));
};

Could you elaborate what type of interoperability are you talking about? Currently, API of JSON-P is very low level. You need to manually add json properties with add method of JsonObjectBuilder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top