Retrieving json from stringified javascript function returned in http response

1.7k views Asked by At

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

There are 1 answers

2
Pointy On

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.