【问题标题】:Loading json files加载 json 文件
【发布时间】:2018-10-15 23:04:59
【问题描述】:

我正在使用 IntelliJ 和 Maven 开发一个 Java 项目,但在将 Json 文件加载和解析到其中时遇到了麻烦。我正在使用 Gson 进行解析。

这是导致问题的代码的sn-p:

 public void parseSomething() {
    Gson gson = new GsonBuilder().create();
    //The Json file contains an array of objects, and I need to put it into a Vector
    Type listType = new TypeToken<List<MyClass>>(){}.getType(); 
    List<MyClass> something = new Vector<>();
    try(Reader file = new FileReader("dir/myFile.json")){
        something = gson.fromJson(file, listType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.something = something; //this sets the attribute of the class
}

我正在使用这个方法来调试它:

public static void main( String[] args ) {
    MyClass myClass = new MyClass();
    myClass.parseSomething();
    String debug = something.toString(); //I've already implemented a custom toString
    System.out.println(debug);
}   

FileNotFoundException 被抛出 try(Reader file = new FileReader("dir/myFile.json"))

如果我的猜测是正确的,程序甚至没有进行解析,因为它找不到文件。

我尝试过的事情:

  1. 使用绝对路径(以及相对路径的细微变化,例如src/main/resources/dir/myFile.jsonresources/dir/myFile.json...)。
  2. 从 intelliJ 和 Maven 设置资源根。
  3. 使用其他方式读取文件,例如:
    • 类加载器
      String fileName = "dir/myFile.json"; ClassLoader classLoader = ClassLoader.getSystemClassLoader(); File file = new File(classLoader.getResource(fileName).getFile());
    • InputStreamReader(我通过这种方式得到一个NullPointerException
      try(Reader reader = new InputStreamReader(myClass.class.getResourceAsStream("dir/myFile.json"))){...}

您知道为什么找不到该文件吗?还有其他方法可以加载吗?

【问题讨论】:

    标签: java json maven intellij-idea gson


    【解决方案1】:

    我相信在 InteliJ 的情况下,Reader 开始在项目的根目录中查找文件,所以是这样的: ./path/to/file/dir/MyFile.json.
    ./ 使它开始查看项目的根文件夹。在/IdeaProjects/MyProject,在这种情况下,它将从MyProject 文件夹开始。

    Similar problem

    【讨论】:

    • 我认为你做对了,因为现在我得到一个 NullPointerException 相对于我猜想的错误解析文件的方式(当我将 json 数组解析为向量时,将包含在向量被初始化?)。但是,如果我在intelliJ和Maven中设置了资源文件夹的相对路径,为什么我不能使用它?
    • @Korax,说实话,我不知道。但如果你有兴趣,我可以提供我的 2 美分。您似乎将something 设置为等于一个新Vector,但您将其声明为List。这个对象的结果永远不会是一个向量,对吧?
    • @Korax >为什么我不能使用资源文件夹的相对路径。你不是唯一一个,也是我经常遇到的问题之一。我曾经使用某种形式的库来为我将资源存储在资源文件夹中。因为我自己永远无法访问它。
    • 不幸的是,即使将 something 声明为 Vector 也会得到 NullPointerException
    • @Korax,这可能是因为在 try catch 块中抛出了异常?所以this.something1 = something2 不起作用,因为something2 从未被初始化,因此调用toString 给出NullPointer?
    猜你喜欢
    • 2015-01-02
    • 2016-01-14
    • 2011-02-22
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    相关资源
    最近更新 更多