Using JSON File in Android App Resources

前端 未结 8 1204
盖世英雄少女心
盖世英雄少女心 2020-11-28 21:00

Suppose I have a file with JSON contents in the raw resources folder in my app. How can I read this into the app, so that I can parse the JSON?

8条回答
  •  青春惊慌失措
    2020-11-28 21:07

    Found this Kotlin snippet answer very helpful ♥️

    While the original question asked to get a JSON String, I figure some might find this useful. A step further with Gson leads to this little function with reified type:

    private inline fun  readRawJson(@RawRes rawResId: Int): T {
        resources.openRawResource(rawResId).bufferedReader().use {
            return gson.fromJson(it, object: TypeToken() {}.type)
        }
    }
    

    Note you want to use TypeToken not just T::class so if you read a List you won't lose the type by type erasure.

    With the type inference you can then use like this:

    fun pricingData(): List = readRawJson(R.raw.mock_pricing_data)
    

提交回复
热议问题