1、Java 代码
第一个示例,通过java将json对象传递给js函数
第二个示例, 将数组传递给js函数,js需要将其中个别位置的字节数组组合后再转回为10进制。
例如,将数组第5和6位,转变为数字, 0xa1, 0x9F, 也就是线组成a19f,然后转换41375。
package com.yq.jsdemo;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Simple to Introduction
* className: JavaJSDemo
*
* @author EricYang
* @version 2018/12/22 9:51
*/
@Slf4j
public class JavaJSListDemo {
private static final String JS_ENGINE_NAME= "nashorn";
private final ScriptEngineManager sem = new ScriptEngineManager();
private final ScriptEngine engine = sem.getEngineByName(JS_ENGINE_NAME);
public static void main(String[] args) {
JavaJSListDemo demo = new JavaJSListDemo();
demo.invokeFunctionByFileWithParams();
demo.invokeFunctionByFileWithListParams();
}
private void invokeFunctionByFileWithParams() {
log.info("--- invokeFunctionWithParams ---" );
try {
log.info("Current dir={}", System.getProperty("user.dir"));
File file = new File("./javademo/src/main/resources/demoWithParams.js");
Reader reader = Files.newBufferedReader(file.toPath(), Charset.defaultCharset());
Object obj1 = engine.eval(reader);
Invocable jsInvoke = (Invocable) engine;
JSONObject user = new JSONObject();
user.put("name", "张三");
user.put("age", 18);
//js函数的就是去user对象age然后加上3
Object obj2 = jsInvoke.invokeFunction("myFunc", user,3);
log.info("function={}, result={}", obj1, obj2);
}
catch(Exception ex) {
log.warn("exception", ex);
}
}
private void invokeFunctionByFileWithListParams() {
log.info("--- With List Params ---" );
try {
log.info("Current dir={}", System.getProperty("user.dir"));
File file = new File("./javademo/src/main/resources/demoWithListParams.js");
Reader reader = Files.newBufferedReader(file.toPath(), Charset.defaultCharset());
Object obj1 = engine.eval(reader);
Invocable jsInvoke = (Invocable) engine;
List dataList = new ArrayList<>();
//15,01,00,00,00,0x0B,01,03,08,01,83,0x63,0x88,02,03,0xEA,0x1B
dataList.add((short)0x15);
dataList.add((short)0x01);
dataList.add((short)0x00);
dataList.add((short)0x00);
dataList.add((short)0x00);
dataList.add((short)0x0B);
dataList.add((short)0x01);
dataList.add((short)0x03);
dataList.add((short)0x08);
dataList.add((short)0x01);
dataList.add((short)0x83);
dataList.add((short)0x63);
dataList.add((short)0x88);
dataList.add((short)0x02);
dataList.add((short)0x03);
dataList.add((short)0xEA);
dataList.add((short)0x1B);
Object obj2 = jsInvoke.invokeFunction("myFunc", Arrays.toString(dataList.toArray()), "device1234");
log.info("function={}", obj1);
log.info("result={}", obj2);
}
catch(Exception ex) {
log.warn("exception", ex);
}
}
}
2、JS代码
2.1demoWithParams.js
传入的user是个json对象, 将user的age属性加上inc然后返回。
function myFunc( user, inc) {
return user.age + inc ;
}
2.2demoWithListParams.js
传入的对象是个数组, 类似"[0x83,0x63,0x88,0x02,0x03,0xEA,0x1B]"。
function myFunc(msgStr, deviceIdStr) {
var scriptInput = JSON.parse(msgStr);
var temperature = scriptInput.slice(9, 13);
var fullTempValArray = temperature.slice(2, 4);
var strArrayTemp = [];
for(var i=0; i<2; i++) {
strArrayTemp.push(fullTempValArray[i].toString(16));
}
//console.log("fullTempValArray:", fullTempValArray, ", strArrayTemp:", strArrayTemp.join(''));
var tempVal = parseInt(strArrayTemp.join(''), 16);
var decimalsNumArray = temperature.slice(1, 2);
//tempVal是显示的值,实际值需要根据decimalsNumArray 进行处理, 这里的处理规则是如果decimalsNumArray 减去128的数字,作为小数位数。 也就是tempVal需要除以多少,例如当decimalsNum等4, tempVal需要除以10000,保留4位小数
var decimalsNum = parseInt(decimalsNumArray.join('')) -128;
var actualTempValue = Number((tempVal / (Math.pow(10, decimalsNum))).toFixed(decimalsNum));
//console.log(actualTempValue)
var humidity = scriptInput.slice(13, 17);
//console.log("-humidity--");
//console.log(humidity);
var fullHumiValArray = humidity.slice(2, 4);
var humiVal = parseInt(fullHumiValArray.join(''), 16);
var strArrayHumi = [];
for(var i=0; i<2; i++) {
strArrayHumi.push(fullHumiValArray[i].toString(16));
}
humiVal = parseInt(strArrayHumi.join(''), 16);
//console.log("fullHumiValArray", fullHumiValArray, fullHumiValArray.join(''), " new:", humiVal)
//console.log("humiVal", humiVal)
decimalsNumArray = humidity.slice(1, 2);
decimalsNum = parseInt(decimalsNumArray.join('')) % 10;
var actualHumiValue = Number((humiVal / (Math.pow(10, decimalsNum))).toFixed(decimalsNum));
//console.log(actualHumiValue);
var data = {}
data.temperature = actualTempValue;
data.humidity = actualHumiValue;
data.deviceId = deviceIdStr;
return JSON.stringify(data);
}