【问题标题】:How to load JSON from string path in Java and print the json values?如何从 Java 中的字符串路径加载 JSON 并打印 json 值?
【发布时间】:2021-07-16 15:34:33
【问题描述】:

我想打印特定 json 文件中的所有 json 对象。 我的函数接收到一个字符串,它是我项目中 json 的路径。 movieListJSON 是我的 json 的路径。

这是我的文件夹结构:

templates
 *fetchIMDB.java
 *Movie.class
movies.json

这是我到目前为止所尝试的,但我没有找到打开 json 并按键遍历值的方法。

public void fetchIMDBMovies(String movieListJSON, String outputDir) throws IOException {
    // 
    JSONObject jsonObject;
    System.out.println(movieListJSON);
    JSONParser parser = new JSONParser();
    InputStream in = getClass().getResourceAsStream(movieListJSON);
}

我的 json 文件如下所示:

    [
 {
  "movie_name": "Avatar"
 },
 {
  "movie_name": "Star Wars VII: The Force Awakens"
 },
 {
  "movie_name": "Pirates of the Caribbean: At World's End"
 },
 {
  "movie_name": "Spectre"
 },
 {
  "movie_name": "The Dark Knight Rises"
 }
]

如何获取所有带有值 movie_name 的 json 并使用 System.out.println() 打印它们;

我想打印电影名称(json 中movie_name 的值)

【问题讨论】:

标签: java json parsing


【解决方案1】:

这是解决方案。

输入文件的路径而不是'your-path'。如果你使用Intelij Idea,你可以通过Right click on file + Copy path... + Copy relative path (或者你想要的完整路径)得到它

 try {
            JSONArray array = (JSONArray) new JSONParser().parse(new FileReader("your-path"));
            for (Object temp : array) {
                JSONObject jsonObject = (JSONObject) temp;
                System.out.println(jsonObject.get("movie_name"));
            }
        } catch (IOException | ParseException  e) {
            e.printStackTrace();
        }

【讨论】:

  • 谢谢。它使用文件的路径而不是字符串作为路径
猜你喜欢
  • 1970-01-01
  • 2016-01-18
  • 2023-01-22
  • 2020-11-19
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-30
相关资源
最近更新 更多