0

I have java (JDK6) code that sends an http get request with parameters. The response that I get back is a javascript function that contains within it a json tree containing the response to the query parameters provided in the request like the following:

function JavascriptFunction() { return { "Root" : [ { ... ] }; }

I am attempting to bind to and execute the returned function using ScriptEngine api in java to retrieve the JSON node.

String response = EntityUtils.toString(httpResponse.getEntity());
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("js");
scriptEngine.eval(response);

String hopeThisIsJson = (String)((Invocable)scriptEngine).invokeFunction("JavascriptFunction");

I get a ClassCastException because the "thing" being returned is of type sun.org.mozilla.javascript.internal.NativeObject.
I am trying to figure out how to ultimately convert this object that is returned from the invokeFunction method a json tree that was originally returned from the "JavascriptFunction" method.

1 Answers1

0

Your JavaScript function is returning an object that is not JSON-encoded. You can try this:

String json = (String) scriptEngine.eval("JSON.stringify(JavascriptFunction());");

There's no such thing as a "JSON tree" in JavaScript code. That's a JavaScript object literal expression, which is to say that it's just a plain JavaScript object.

Pointy
  • 371,531
  • 55
  • 528
  • 584
  • I tried what you suggested. I get javax.script.ScriptException... ReferenceError: "JSON" is not defined. The Rhino engine I have may not support the version of Javascript in which "JSON" exists. In this case, I have to assume I cannot change versions. Any alternatives to making using this? – user2714310 Aug 26 '13 at 06:05
  • 1
    @user2714310 yes, you need a 1.7 release of Rhino at least. If you can't change versions, you'll have to use a JSON toolkit, like the one available at json.org. – Pointy Aug 26 '13 at 13:50
  • Thanks for the info. I'll look into it. – user2714310 Aug 27 '13 at 16:31