jython返回值之解析
使用jython脚本就是为了更好的扩展和控制,返回的类型也就要做相应的处理了:
package com;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Jython常用用法Test
*
* @author Administrator
*
*/
public class ForJavaTest {
public static void main(String[] args) throws PyException {
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("./src/com/test.py");
// 数据统计(用于数据,<0 输出-1.> 2 输出0 到 实际输出值 的和)
PyFunction pyFunction = (PyFunction) interp.get("getValue",
PyFunction.class);
System.out.println("Result: " + pyFunction.__call__(new PyInteger(5)));
// 动态获取最新配置的方法
PythonInterpreter interp1 = new PythonInterpreter();
interp1.exec("import re");
interp1.execfile("./src/com/configValue.py");
PyFunction pyFunction1 = (PyFunction) interp1.get("getConfig",
PyFunction.class);
System.out.println("config value: "
+ pyFunction1.__call__(new PyString("MaxValue")));
// 进行复杂类接受处理
Map<String, Object> res = new HashMap<String, Object>();
res.put("1", "Danny");
res.put("2", "Fanny");
PythonInterpreter interpM = new PythonInterpreter();
interpM.execfile("./src/com/DataDeal.py");
PyFunction pyFunctionM = (PyFunction) interpM.get("main",
PyFunction.class);
Map<PyObject, PyObject> tableM = new HashMap<PyObject, PyObject>();
tableM.put(new PyString("conf"), PyJavaType.wrapJavaObject(res));
PyDictionary pydM = new PyDictionary(tableM);
PyObject obj = pyFunctionM.__call__(pydM);
Map<String, Object> resu;
PyDictionary resMap = (PyDictionary) obj;
resu = processResult(resMap);
System.out.println(resu);
}
public static Map<String, Object> processResult(PyDictionary obj) {
Map<String, Object> res = new HashMap<String, Object>();
Iterator<String> keyIter = obj.keySet().iterator();
System.out.println("=======java=====");
while (keyIter.hasNext()) {
String key = keyIter.next();
PyString pykey = new PyString(key);
PyObject pyvalue = obj.get(pykey);
System.out.println(pykey);
System.out.println(pyvalue);
if (pyvalue instanceof PyList) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
PyObject[] dataList = ((PyList) pyvalue).getArray();
int i = 0;
while (i < dataList.length) {
System.out.println(dataList[i]);
list.add(processResult((PyDictionary) dataList[i]));
i++;
}
res.put(key, list);
System.out.println("+++++++result+++++");
} else if (pyvalue instanceof PyString) {
try {
res.put(key, new String(((PyString) pyvalue).toBytes(),
"utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
res.put(key, pyvalue.toString());
}
}
return res;
}
}
其中复杂类型就涉及到递归的运算了,但在实际中由于版本的不同,返回的类型的处理就可能
换种方式了
// 获取jythond返回的总数据
PyObject[] dataList = ((PyList) obj).getArray();
list = processResult((PyDictionary) dataList[0]);