首页 > 解决方案 > 在 Python 脚本和 Java 控制器之间传递 JSON

问题描述

快速背景故事——我正在使用 MVC 结构和 Spring Framework 构建一个 Java Web 应用程序。我的控制器对象调用一个 Python 脚本,该脚本查询一堆 API 并返回我想在我的 Java 文件中捕获和使用的 JSON 有效负载。

在汇总了来自几个不同来源的信息之后,这是我目前所拥有的:

        String currQuery = "cmd /c python ../../../../python/state/main.py";
        Process p = Runtime.getRuntime().exec(currQuery);
        p.waitFor();

        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

如您所见,这将打印脚本返回值的每一行。但是,我想要的是能够在我的 Java 类中与 main.py 返回的 JSON 对象进行交互。

在正在执行的 python 文件和我的 Java 类之间传递 JSON 对象的最佳方法是什么?

也许使用JSONReader?任何意见/建议将不胜感激,如果需要更多信息,请告诉我。

标签: javajson

解决方案


推荐阅读