Read a json file from the assets folder in Android

This code snippet will read a json file at app/assets/data/data.json into a string.

String json = null;
try {
    InputStream is = getAssets().open("data/data.json");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();
    json = new String(buffer, "UTF-8");
} catch (IOException ex) {
    ex.printStackTrace();
}

If you have a pojo class for example Data.java that models the data in the json, and you are you gson to convert the json string into the Data class. Then you can do it by this line.

Data data = new Gson().fromJson(json, Data.class);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search