因為js 有自己的特性,我們一般對於map 參數的傳遞通過ProxyObject.fromMap 處理,以下是一個demo
基本使用
- 參考代碼
public static void es6Rollup2(Engine engine) throws IOException {
Context context = Context.newBuilder().allowAllAccess(true).allowHostClassLoading(true).allowIO(true).allowNativeAccess(true).engine(engine).build();
Source mysource = Source.newBuilder("js","load(\"src/main/resources/mydemoapp.js\");","demoapp").mimeType("application/javascript+module").build();
context.eval(mysource);
Value callapp = context.getBindings("js").getMember("window");
Value result = callapp.getMember("demo");
Map<String,Object> ob =new HashMap<>();
Map<String,Object> ob2 =new HashMap<>();
ob2.put("url","https://plus.google.com/102817283354809142195/posts/F97fqZwJESL");
ob.put("url","https://plus.google.com/102817283354809142195/posts/F97fqZwJESL");
Map<String,Object> ob3 =new HashMap<>();
ob3.put("url","https://plus.google.com/102817283354809142195/posts/F97fqZwJESL");
ob2.put("ob",ProxyObject.fromMap(ob3));
ob.put("id","z12gtjhq3qn2xxl2o224exwiqruvtda0i");
ob.put("object",ProxyObject.fromMap(ob2));
String filed = "url,object(url,ob/url)";
System.out.println(ob.toString());
String info ="{\"id\":\"z12gtjhq3qn2xxl2o224exwiqruvtda0i\",\"url\":\"https://plus.google.com/102817283354809142195/posts/F97fqZwJESL\",\"object\":{\"objectType\":\"note\",\"content\":\"A picture... of a space ship... launched from earth 40 years ago.\",\"attachments\":[{\"objectType\":\"image\",\"url\":\"http://apod.nasa.gov/apod/ap110908.html\",\"image\":{\"height\":284,\"width\":506}}]},\"provider\":{\"title\":\"Google+\"}}";
Value execResult =result.execute(ProxyObject.fromMap(ob),filed);
System.out.println(execResult);
}
- 說明
通過ProxyObject處理,但是因為默認ProxyObject.fromMap 不會進行深復制處理,如果我們是嵌套的就需要多次處理
同時以上的js 代碼如下(使用了json-mask 處理json 內容,java 調用通過browserify 進行了轉換,具體可以參考https://www.cnblogs.com/rongfengliang/p/13584488.html)
const mask = require("json-mask")
module.exports = {
maskfn: function (datas, fields) {
return mask(datas, fields)
}
}
window = this || {}
window.demo = function (datas, fields) {
let mydatas
mydatas = datas;
if (typeof datas === 'string') {
mydatas =JSON.parse(datas)
}
return mask(mydatas, fields)
}
- 運行效果
說明
實際上官方也有相關的特性開關,可以實現自動的處理,還沒測試,后邊測試下