How to properly implement JSObject to provide conversion of Gson JsonElement objects?

Daniel Einspanjer deinspanjer at
Thu May 25 19:57:46 UTC 2017

I have a project that makes extensive use of the Google Gson library.

In this particular case, I have a JsonArray object (which implements
iterable) containing a collection of objects.  In pure JSON it would look
like this:

[ 1, true, {"a": "b"}, [1,2] ]

In Gson JsonElements, it looks like this:

arr = new JsonArray();

obj = new JsonObject();
obj.addProperty("a", "b");


innerArr = new JsonArray();


I am calling a Javascript function in Nashorn that is trying to do a map
over this array:

nash.eval("function doIt(arr) { print( { return
(typeof item); })); }");

So, in order for this to work with my own arbitrary object (JsonArray), I
believe I need to implement JSObject.

I created the wrapper class that implements it, using the underlying
JsonArray object as a delegate.  things like isArray() and such are
trivial, but I'm having trouble with the map.
I have a map method that takes a functional interface which is available
for the JsonArray object.

Nashorn calls getMember("map") when the doIt function is executed.  I
cannot figure out how to give it an appropriate function reference to my method.
I was able to handle getMember("toString") easily enough, but the problem
is that method doesn't take any arguments, so returning a simple
Callable<Object> is fine for it, but map is going to take arguments that I
don't know about ahead of time.

I would really appreciate some assistance here.  Thanks.


More information about the nashorn-dev mailing list