Read JSON file from assets

S A Z I B
2 min readApr 14, 2021

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

Put a .json file in your project’s assets folder. If asset folder is not there create one.

country.json

country.json file contains data like below:

[
{
“name”: “Afghanistan”,
“dialCode”: “+93”,
“isoCode”: “AF”,
“flag”: “https://www.countryflags.io/AF/flat/64.png"
},
{
“name”: “Aland Islands”,
“dialCode”: “+358”,
“isoCode”: “AX”,
“flag”: “https://www.countryflags.io/AX/flat/64.png"
}]

Now let’s create a kotlin data class.

data class Country(
@SerializedName("dialCode") @Expose var dialCode: String? = null,
@SerializedName("flag") @Expose var flag: String? = null,
@SerializedName("isoCode") @Expose var isoCode: String? = null,
@SerializedName("name") @Expose var name: String? = null
)

Now let’s create a function to read the .json file.

fun getCountryCode(context: Context): List<Country> {

lateinit var jsonString: String
try {
jsonString = context.assets.open("country/country.json")
.bufferedReader()
.use { it.readText() }
} catch (ioException: IOException) {
AppLogger.d(ioException)
}

val listCountryType = object : TypeToken<List<Country>>() {}.type
return Gson().fromJson(jsonString, listCountryType)
}
//here Gson() is basically providing fromJson methods which actually //deserializing json. It basically parse json string to //list<Country> object
//this getCountryCode(ctx: Context) will return a list of Country data class.

Summary:

  • put assets folder and a JSON file the assets folder
  • create a data class
  • use AssetManager to open the File, then get JSON string
  • use Gson to parse JSON string to Kotlin object

--

--