1 创建maven项目
在pom.xml文件中添加相应库:
<dependencies>
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
<!-- JSONObject对象依赖的jar包 -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier><!-- 指定jdk版本 -->
</dependency>
<!-- Json依赖架包下载 -->
</dependencies>
2 创建ok.py文件,该文件位置需要直接放置在项目目录中
#-*- coding: UTF-8 -*-
import json
def hello(x):
y=json.loads(x)
return r'{k1:"成功没有%d", str:"%s"}'%(y["xid"],y["xname"])
3 创建java调用代码
import net.sf.json.JSONObject;
import org.python.core.*;
import org.python.util.PythonInterpreter;
public class ok {
//调用python语句
public void py01(){
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('hello')");
}
// 调用python脚本
public void py02(){
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("ok.py");
PyFunction pyFunction = interpreter.get("hello", PyFunction.class); // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
String s="{\"xid\":18,\"xname\":\"你好\"}";
PyString str = Py.newStringUTF8(s);
PyObject pyObject = pyFunction.__call__(str); // 调用函数
JSONObject obj=new JSONObject();
System.out.println(pyObject);
}
public static void main(String[] args) {
ok k=new ok();
k.py02();
}
}
执行返回结果:
{k1:"æ��å��没æ��18", str:"你好"}