evgenyneu / js-evaluator-for-android

A library for running JavaScript in Android apps.
MIT License
485 stars 84 forks source link

pass json object #14

Open mahmoud-elnaggar opened 9 years ago

mahmoud-elnaggar commented 9 years ago

why this simple code doesn't work String jsCode = "function func(answers){ return answers[100];}"; jsEvaluator.callFunction(jsCode, new JsCallback() {

                    @Override
                    public void onResult(final String result) {
                        UIUtils.showToast(getActivity(), result);
                    }
                }, "func", "{\"100\":\"hello\",\"200\":\"HI\"}");

note that I pass json object but JsEvaluator consider it as string

evgenyneu commented 9 years ago

Hi, the library does not support passing objects as function parameters - only strings and numbers.

mahmoud-elnaggar commented 9 years ago

OK thanks can you tell me if any library can take objects as parameters

evgenyneu commented 9 years ago

No idea, sorry.

AndreiDuma commented 9 years ago

You can send the object serialized as JSON and parse it in the code. Then serialize the result and return as string.

mahmoud-elnaggar commented 9 years ago

@AndrieDuma that's what I did to solve it, Thanks for your suggestion also I found that I can pass json array but I need to use eval(params) in my JavaScript so I can handle it as array

evgenyneu commented 9 years ago

@AndreiDuma thank you, I think I will add instructions to the readme. It is probably much easier to convert JSON to object and back in JavaScript than doing it Java.

AndreiDuma commented 9 years ago

You can do it like this:

public static final String WRAPPER = "function __wrapper__(s) {" +
            "var input = JSON.parse(s);" +
            "var output = process(input);" +
            "return JSON.stringify(output);" +
            "}";
public static final String FUNC_NAME = "__wrapper__";
// ...
String source = task.getCode() + Constants.WRAPPER;
String input = task.getInput();

jsEvaluator.callFunction(source, new JsCallback() {
    @Override
    public void onResult(final String result) {
        // ...
    }
}, FUNC_NAME, input);

The code must contain a function called process and the task.getInput() must return valid JSON.