Home > Software design >  How to read a json file from resources without application context
How to read a json file from resources without application context

Time:08-11

I'm trying to read a json file from res/raw folder, but I'm not in an Activity, it's in a Kotlin object. I can't manage to read it without context or applicationContext which I don't have there.

I tried to create a class where I inject the context with Hilt, but that failed too because I can't inject that class in my object. I'm stuck, what am I missing? It can't be that difficult?

The json file is currently only

{
   "spacer": 8
}

Perhaps in the future some more parameters will be added. I want to save this value in an object (which contains other values not from json) so I don't have to read it every time it's needed. The parameter is used in a Compose theme.

CodePudding user response:

You could try to use a context extension function to read your json file from /assets folder:

fun Context.getJsonFromAssets(fileName: String): String? {
    val jsonString: String
    try {
        val inputStream = assets.open(fileName)

        val size = inputStream.available()
        val buffer = ByteArray(size)
        inputStream.read(buffer)
        inputStream.close()

        jsonString = String(buffer, Charset.defaultCharset())
    } catch (e: IOException) {
        e.printStackTrace()
        return null
    }

    return jsonString
}

CodePudding user response:

if you are using Koin you could do something like this:

import android.content.Context
import com.your.app.R
import org.koin.java.KoinJavaComponent.get

object YourObject {

  val context: Context = get(Context::class.java)
  val yourString = context.getString(R.string.your_string)

  // do other stuff with context here

}

you should just take care not to store this context object because it could cause memory leaks, you could just use it to get your resource without assigning it to any variables like

val yourString = get(Context::class.java).getString(R.string.your_string)
  • Related