Issue
I want to be able to deploy my spring boot application onlne on heroku. My app loads data from a static .json file which is located on my resources folder.
alt="enter image description here">
So far I've tried this code but it doesn't work. For some reason I can't read the data from the json file.
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;
}
Solution
Since data.json
is moved inside JAR which is deployed on heroku, try using getResourceAsStream(path)
instead getResource()
. pseudocode could be,
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());
Answered By - benjamin c
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)