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?
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)