'How to read data from JSON file on the resources directory?

How to read data from JSON file on the resources directory? I need to read a json file on the resources directory, convert it to a data class ("User") I'm trying to adapt the following code

private fun getJSONFromAssets(): String? {

    var json: String? = null
    val charset: Charset = Charsets.UTF_8
    try {
        val myUsersJsonFile = assets.open("users.json")
        val size = myUsersJsonFile.available()
        val buffer = ByteArray(size)
        myUsersJsonFile.read(buffer)
        myUsersJsonFile.close()
        json = String(buffer, charset)
    } catch (ex: IOException) {
        ex.printStackTrace()
        return null
    }
    return json
}

but assets.open("users.json") is not recognized. How is the best approach to read JSON files on the resources directory (mock data)?



Solution 1:[1]

You just need a minor change in your function...

private fun getJSONFromAssets(context: Context): String? {
    ...
    val myUsersJsonFile = context.assets.open("users.json")
    ...
}

Assuming that your json file is at src/main/assets.

If you need to read a JSON file from the src/main/res/raw folder. You can use:

private fun getJSONFromAssets(context: Context): String? {
    ...
    val myUsersJsonFile = context.resources.openRawResource(R.raw.users)
    ...
}

As you can see, you need a Context, so you can call from your activity.

getJSONFromAssets(this) // "this" is your activity (or another Context)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nglauber