Java Android – Read JSON file from assets using Gson

In this Java-Android tutorial, I will show you how to read and parse JSON file from assets using Gson.

Where to put assets folder and JSON file

You will need to create the assets folder inside src/main, together with java and res folder. Then put JSON file inside assets folder.

java-android-read-json-file-assets-gson-assets-location

For example, bezkoder.json file contains list of people data like this.

[
  {
    "name": "bezkoder",
    "age": "26",
    "messages": [
      "hi",
      "My name is zKoder"
    ]
  },
  {
    "name": "bezkoder Master",
    "age": 30,
    "messages": [
      "becoming Java Master",
      "still learning Java"
    ]
  }
]

Create Java Data Class

Let’ create User class with 3 fields: name, age, messages.

User.java

import java.util.List;

public class User {
  String name;
  int age;
  List<String> messages;

  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;
  }

  public List<String> getMessages() {
    return messages;
  }

  public void setMessages(List<String> messages) {
    this.messages = messages;
  }

  @Override
  public String toString() {
    return "User{" +
        "name='" + name + '\'' +
        ", age=" + age +
        ", messages=" + messages +
        '}';
  }
}

Create function for reading JSON file from assets

Let’s a Utils class and add a static function that will read JSON file from assets.

Utils.java

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

public class Utils {

  static String getJsonFromAssets(Context context, String fileName) {
    String jsonString;
    try {
      InputStream is = context.getAssets().open(fileName);

      int size = is.available();
      byte[] buffer = new byte[size];
      is.read(buffer);
      is.close();

      jsonString = new String(buffer, "UTF-8");
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

    return jsonString;
  }
}

You can see that getJsonFromAssets() function has 2 parameters: context & fileName.
– We get AssetManager object from context by context.assets, then use AssetManager.open() method to open a file in assets folder using ACCESS_STREAMING mode, it returns an InputStream.
– Then we use InputStream.read() to read data into byte[] buffer and readText() to transform the buffer into a String.

Parse JSON using Gson

Gson.fromJson() method

com.google.gson.Gson package provides fromJson() for deserializing JSON.

public <T> T fromJson(java.lang.String json,
                      java.lang.Class<T> classOfT)
               throws JsonSyntaxException;

public <T> T fromJson(java.lang.String json,
                      java.lang.reflect.Type typeOfT)
               throws JsonSyntaxException
  • T: type of the desired object
  • json: could be a JsonElement object, a Reader object or a String
  • classOfT: class of T
  • typeOfT: specific genericized type

Add Gson to Android project

Gson is a Java library for converting JSON string to an equivalent Java object.
Open build.gradle file and add Gson library.

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

Parse JSON string to Java object

In your activity, import Gson library and call getJsonFromAssets().

// ...
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "bezkoder.json");
Log.i("data", jsonFileString);

Gson gson = new Gson();
Type listUserType = new TypeToken<List<User>>() { }.getType();

List<User> users = gson.fromJson(jsonFileString, listUserType);
for (int i = 0; i < users.size(); i++) {
  Log.i("data", "> Item " + i + "\n" + users.get(i));
}

Now, open Android Logcat window and you can see:

01-08 23:55:11.986 11885-11885/com.bezkoder.readjson I/data: [
      {
        "name": "bezkoder",
        "age": "26",
        "messages": [
          "hi",
          "My name is zKoder"
        ]
      },
      {
        "name": "bezkoder Master",
        "age": 30,
        "messages": [
          "becoming Java Master",
          "still learning Java"
        ]
      }
    ]
01-08 23:55:12.040 11885-11885/com.bezkoder.readjson I/data: > Item 0
    User{name='bezkoder', age=26, messages=[hi, My name is zKoder]}
01-08 23:55:12.040 11885-11885/com.bezkoder.readjson I/data: > Item 1
    User{name='bezkoder Master', age=30, messages=[becoming Java Master, still learning Java]}

Conclusion

Let me summarize what we’ve done in this tutorial:

  • put assets folder & JSON file in the right place
  • create data class corresponding to JSON content
  • use AssetManager to open the File, then get JSON string
  • use Gson to parse JSON string to Java object

Happy Learning! See you again.

Further Reading

5 thoughts to “Java Android – Read JSON file from assets using Gson”

  1. Excellent Tutorial 🙂
    Simple and very easy steps to follow through.

    Thanks a lot.

Comments are closed to reduce spam. If you have any question, please send me an email.