S. Benson
S. Benson

Reputation: 13

How to programmatically import a local JSON file?

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.

Upvotes: 0

Views: 204

Answers (2)

Aelphaeis
Aelphaeis

Reputation: 2613

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'

Upvotes: 1

Karsh Soni
Karsh Soni

Reputation: 170

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.

Upvotes: 1

Related Questions