I would like to import a local JSON-file from my assets folder, but i don´t know how to do and which packages I have to import. I couldn´t find anything useful about this.
Asked
Active
Viewed 194 times
0
-
What do you mean by "import"? Do you want your app to read that at runtime? – GhostCat Mar 12 '19 at 18:23
-
are you trying to ask that you have saved a local JSON file into your asset and want to read that file runtime? – Karsh Soni Mar 12 '19 at 18:25
-
It's hard to understand and help you when you provide less details. Please provide more details. – Uma Sankar Mar 12 '19 at 18:37
-
Similar question with answer here, https://stackoverflow.com/questions/9544737/read-file-from-assets – Harshith Shetty Mar 12 '19 at 18:47
2 Answers
1
If you meant that you have a JSON file saved into asset folder and you want to read that during runtime then what you can do is ... 1 -> Read that file as it contains string and then as we know that every json will start from object or array. so, then you can convert that string into object or an array.
You can use something similar to this.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(string);
Where string is the json string.
Try this and let me know if you need anything thanks. Happy Coding.

Karsh Soni
- 170
- 1
- 12
1
You can use Gson to do this if your assets have an object representation :
public <T> T fromFile(Class<T> type, String location) throws IOException {
try(FileReader fr = new FileReader(location)){
return new Gson().fromJson(fr, type);
}
}
e.g :
public static void main(String[] args) throws IOException { Person p = fromFile(Person.class, "src/main/resources/data.json"); System.out.print(p); } public static <T> T fromFile(Class<T> type, String location) throws IOException { try(FileReader fr = new FileReader(location)){ return new Gson().fromJson(fr, type); } } public static class Person{ String name; int age; public Person(String name, int age) { this.age = age; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
This is the dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
or if using gradle
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

Aelphaeis
- 2,593
- 3
- 24
- 42