Kotlin Android – Read JSON file from assets using Gson

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

Related Posts:
Kotlin – Convert object to/from JSON string using Gson
How to read File in Kotlin

Where to put assets folder and JSON file

You will need to create the assets folder inside src/main, next to your java and res folder. Then make sure that your JSON file is within your assets folder.

kotlin-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": [
      "hello",
      "becoming zKoder"
    ]
  },
  {
    "name": "bezkoder Master",
    "age": 30,
    "messages": [
      "I am Kotlin Master",
      "still learning Kotlin"
    ]
  }
]

Create Data Class

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

Person.kt

data class Person(val name: String, val age: Int, val messages: List) {
}

Create function for reading JSON file from assets

We’re gonna create a Utils class and add the function that will read JSON file from assets.

Utils.kt

import android.content.Context
import java.io.IOException

fun getJsonDataFromAsset(context: Context, fileName: String): String? {
    val jsonString: String
    try {
        jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() }
    } catch (ioException: IOException) {
        ioException.printStackTrace()
        return null
    }
    return jsonString
}

The 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 bufferedReader() creates a buffered reader on the InputStream and readText() helps us to read this reader as a String.

Parse JSON using Gson

Gson.fromJson() method

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

public <T> T fromJson​(json, classOfT) throws JsonSyntaxException
public <T> T fromJson​(json, 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/Kotlin library for converting JSON string to an equivalent Java/Kotlin object.
Open build.gradle file and add Gson library.

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

Parse JSON string to Kotlin object

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

// ...
import android.util.Log

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

val jsonFileString = getJsonDataFromAsset(applicationContext, "bezkoder.json")
Log.i("data", jsonFileString)

val gson = Gson()
val listPersonType = object : TypeToken<List<Person>>() {}.type

var persons: List<Person> = gson.fromJson(jsonFileString, listPersonType)
persons.forEachIndexed { idx, person -> Log.i("data", "> Item $idx:\n$person") }

Check Android Logcat, you can see:

01-08 11:53:37.314 9971-9971/com.bezkoder.jsonfile I/data: [
      {
        "name": "bezkoder",
        "age": "26",
        "messages": [
          "hello",
          "becoming zKoder"
        ]
      },
      {
        "name": "bezkoder Master",
        "age": 30,
        "messages": [
          "I am Kotlin Master",
          "still learning Kotlin"
        ]
      }
    ]
01-08 11:53:37.444 9971-9971/com.bezkoder.jsonfile I/data: > Item 0:
    Person(name=bezkoder, age=26, messages=[hello, becoming zKoder])
01-08 11:53:37.444 9971-9971/com.bezkoder.jsonfile I/data: > Item 1:
    Person(name=bezkoder Master, age=30, messages=[I am Kotlin Master, still learning Kotlin])

In the code above, we use Gson.fromJson() method to parse JSON string to List<Person>.

For more details about ways to parse JSON to Data Class object, to Array or Map, please visit:
Kotlin – Convert object to/from JSON string using Gson

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 Kotlin object

Happy Learning! See you again.

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *