java通过jep调用python脚本,python脚本执行后返回一个bytes类型的对象,最终希望转为java的byte[]存进数据库,java该如何接收?
python代码
import pickle
import ast
def dumps(param):
# 字符串转为字典对象
dict_param = ast.literal_eval(param)
# 字典对象转为二进制对象
bin_param = pickle.dumps(dict_param)
return bin_param
java代码,目前通过String接收,但是会报错
MainInterpreter.setJepLibraryPath("D:\\program\\Python\\Lib\\site-packages\\jep\\jep.dll");
Map<String, Object> map = new HashMap<>();
map.put("param", value);
String result = JepUtils.execJepScript(
() -> Lists.newArrayList("from python_parameter.dumps_parameter import dumps"),
() -> map,
() -> "dumps(param)", String.class);
补充:
尝试过在python代码中将bytes转为str,java以String接收后再转为byte[],但发现并不是想要的结果,代码如下:
import pickle
import ast
def dumps(param):
# 字符串转为字典对象
dict_param = ast.literal_eval(param)
# 字典对象转为二进制对象
bin_param = pickle.dumps(dict_param)
# 二进制对象转为str
return str(bin_param)
public byte[] dumps(String value) {
try {
MainInterpreter.setJepLibraryPath("D:\\program\\Python\\Lib\\site-packages\\jep\\jep.dll");
Map<String, Object> map = new HashMap<>();
map.put("param", value);
String result = JepUtils.execJepScript(
() -> Lists.newArrayList("from python_parameter.dumps_parameter import dumps"),
() -> map,
() -> "dumps(param)", String.class);
return hexStringToBytes(result);
} catch (JepException e) {
e.printStackTrace();
}
return null;
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}