我希望能夠在 heroku 上在線部署我的 Spring Boot 應用程序。我的應用程序從位于我的資源文件夾中的靜態 .json 文件加載數據。到目前為止,我已經嘗試過這段代碼,但它不起作用。出于某種原因,我無法從 json 文件中讀取數據。 public List<Category> getAllCategories() throws FileNotFoundException { Gson gson = new Gson(); ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("static/data/data.json").getFile()); JsonReader reader = new JsonReader(new FileReader(file.getPath())); List<Category> allCategories = gson.fromJson(reader, new TypeToken<List<Category>>(){}.getType()); return allCategories; }
2 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
由于data.json移動它被部署在Heroku里面JAR,請嘗試使用getResourceAsStream(path)替代getResource()。偽代碼可能是,
Gson gson = new Gson();
ClassLoader classLoader = getClass().getClassLoader();
InputStream in = classLoader.getResourceAsStream("static/data/data.json");
JsonReader reader = new JsonReader(new InputStreamReader(in));
List<Category> allCategories = gson.fromJson(reader, new TypeToken<List<Category>>(){}.getType());

慕少森
TA貢獻2019條經驗 獲得超9個贊
您能否將數據文件夾直接移動到資源下,因為靜態資源路徑在這里可能會發生沖突,下面的使用應該可以工作。
File file = new File(classLoader.getResource("data/data.json").getFile());
添加回答
舉報
0/150
提交
取消