How to read json file from assests in android using Kotlin?
Asked Answered
R

5

6

I have already done with java but find difficult with Kotlin.

I have already search with google but none of them work for me.

/**
 * Get the json data from json file.
 *
 * @param context  the context to acces the resources.
 * @param fileName the name of the json file
 * @return json as string
 */
public static String getJsonFromAsset(Context context, String fileName) {
    String json = "";
    try {
        InputStream stream = context.getAssets().open(fileName);
        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        json = new String(buffer, "UTF-8");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

I want this code in Kotlin.

Retroflexion answered 10/7, 2019 at 2:21 Comment(1)
Please see this way : https://mcmap.net/q/117063/-how-to-parse-json-in-kotlinEgest
T
20

Reading json file from assets folder in Kotlin is very easy, just use the following code

val fileInString: String =
  applicationContext.assets.open(fileName).bufferedReader().use { it.readText() }
Tape answered 10/7, 2019 at 6:3 Comment(0)
M
4

Java codes can be converted to Kotlin from Android Studio too. Here is the converted solution with the extension function of Context.

@Throws(IOException::class)
fun Context.readJsonAsset(fileName: String): String {
    val inputStream = assets.open(fileName)
    val size = inputStream.available()
    val buffer = ByteArray(size)
    inputStream.read(buffer)
    inputStream.close()
    return String(buffer, Charsets.UTF_8)
}
Mikamikado answered 10/7, 2019 at 2:42 Comment(0)
G
1

You can use the following

class LocalJSONParser {

companion object {
    fun inputStreamToString(inputStream: InputStream): String {
        try {
            val bytes = ByteArray(inputStream.available())
            inputStream.read(bytes, 0, bytes.size)
            return String(bytes)
        } catch (e: IOException) {
            return ""
        }
      }
    }
}

// jsonFileName = "data.json"
inline fun <reified T> Context.getObjectFromJson(jsonFileName: String): T {
val myJson =LocalJSONParser.inputStreamToString(this.assets.open(jsonFileName))
return Gson().fromJson(myJson, T::class.java
}
Grouchy answered 11/7, 2019 at 17:57 Comment(0)
S
1

To guarantee testability and maintainability, I would suggest to make interface with readJsonFile function:

interface JsonAssets {
  suspend fun readJsonFile(fileName: String): Result<SomeData>
}

In the implementation details, to perform file reading in a thread-safety, I used Coroutine with withContext(Dispatchers.IO). This provides the block of code runs on the background thread.

class DefaultJsonAssets : JsonAssets {

override suspend fun readJsonFile(fileName: String): Result<Cookie> = withContext(Dispatchers.IO) {
    try {
      val classLoader = javaClass.classLoader
      val inputStream: InputStream? = classLoader?.getResourceAsStream(fileName)

      if (inputStream != null) {
        val jsonString = inputStream.bufferedReader().use { it.readText() }
        val cookie = Json.decodeFromString(SomeDataSerializer, jsonString)
        Result.success(cookie)
      } else {
        Result.failure(Exception("File not found: $fileName"))
      }
    } catch (e: Exception) {
      Result.failure(e)
    }
  }

If the file is found, it reads the content, deserializes it into a SomeData using a Json decoder, and returns a Result.success. If the file is not found, it returns a Result.failure with an appropriate exception.

Sappy answered 18/1, 2024 at 4:21 Comment(0)
R
0
fun loadAssetsFromFile ( context : Context ) {

    val inputStream = context.assets.open("example.json")
    val size = inputStream.available()
    val buffer = ByteArray(size)
    inputStream.read(buffer)
    inputStream.close()
    val json = String(buffer, charset = UTF_8)
    val gson = Gson()
    data = gson.fromJson(json, Array<Quote>::class.java)
}
Refection answered 26/8, 2024 at 7:11 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Anni

© 2022 - 2025 — McMap. All rights reserved.