最近,在項目中需要用到Java代用Python的代碼,並且需要傳參數,因此選用了Jython包,但是,如果在調用python腳本時,出現了中文亂碼的現象。代碼如下:
PythonInterpreter interpreter = interpreter = new PythonInterpreter();
String code = "# -*- coding: utf-8 -*-\n" +
"import sys\n" +
"reload(sys)\n" +
"sys.setdefaultencoding('utf-8')\n" +
"import json\n" +
"def parse(strtest):\n" +
" jsonObj = json.loads(strtest)\n" +
" jsonObj[\"省份\"] = \"安徽省\"\n" +
" return json.dumps(jsonObj)";
interpreter.exec(code);
PyFunction func = (PyFunction)interpreter.get("parse",PyFunction.class);
String str = "{\"CityId\":18,\"CityName\":\"合肥\",\"ProvinceId\":27,\"CityOrder\":1}";
PyString str2 = Py.newStringOrUnicode(str);
PyObject pyObject = func.__call__(str2);
JSONObject json = new JSONObject(pyObject.toString());
System.out.println(json.toString());
運行結果如下:
![]()
結果很奇怪,傳進去的參數中有中文不亂碼,但是寫在腳本中的中文亂碼了,開始以為是Python腳本中編碼的設置問題,上網搜了很久,答案都是在腳本中加入
# -*- coding: utf-8 -*- 或者sys.setdefaultencoding('utf-8')之類的,但是都沒有效果。后來想了想,是不是代碼中的code腳本傳進Jython包中不是utf-8編碼的問題,因此試了試把code
腳本寫在文件中,並制定文件為utf-8編碼,使用:interpreter.execfile(“E:\\test.py”)調用腳本執行,結果中文不亂碼了。
雖然上述方法解決了問題,但是如果每次動態執行腳本時,都需要先把腳本存到.py文件中,然后在調用,這樣會很麻煩。
因此,研究了下Jython包,發現在講Java的字符串傳進Jython包中時,可以先轉化為PyString,並指定編碼,因此,修改上述程序。

運行結果如下:
![]()
