java调用python脚本,json传参方式。

使用python的json.loads()进行解析json数据,如果没有包含双引号,则会解析出错

解决方案1

使用demjson.decode(),安装方式直接百度,就不做过多的说明了

解决方案2

使用json.loads()方式解析,下面是我的python代码

import json
import sys

def analysis():
    data2 = json.loads(sys.argv[1])["param"]
    for data in data2:
        print("vce: %s, tj: %s, tcc: %s."%(data["vce"],data["tj"],data["tcc"]))

if __name__ == '__main__':
     analysis()

使用Jackson的ObjectMapper类, 使用objectMapper.writeValueAsString(params).replace(“”“, “\””);

下面是我的调用代码

  public static void main(String[] args) throws FileNotFoundException {
    
    
//        File file = new File("E:\\workplace_module\\DataAnalysisProject\\src\\main\\resources\\xlsx\\电容老化数据.xlsx");
//        List<DianRongCAndESR> dianRongCAndESRS =  DianRongAnalysis(2,new FileInputStream(file));
//        System.out.println(dianRongCAndESRS);

        File file = new File("E:\\workplace_module\\DataAnalysisProject\\src\\main\\resources\\xlsx\\IGBT老化数据.xlsx");
        List<IGBTExcelParams> dianRongCAndESRS =  IGBTAnalysis(new FileInputStream(file));
        AnalysisVo<IGBTExcelParams> vo = new AnalysisVo();
        vo.setParam(dianRongCAndESRS);
        ObjectMapper objectMapper = new ObjectMapper();
        Process proc;
        try {
    
    
            String json = objectMapper.writeValueAsString(vo).replace("\"", "\\\"");
            String[] cmdarray = new String[]{
    
    "python", "C:\\Users\\test1\\PycharmProjects\\pythonProject1\\test.py", json};
            ProcessBuilder pb = new ProcessBuilder(cmdarray);
            proc = pb.start();
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = in.readLine()) != null) {
    
    
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }

运行结果

是能够获取到python打印的结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42900469/article/details/131571290