简体   繁体   中英

Retrieving json from stringified javascript function returned in http response

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM