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?
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 <reified T> readRawJson(@RawRes rawResId: Int): T {
resources.openRawResource(rawResId).bufferedReader().use {
return gson.fromJson<T>(it, object: TypeToken<T>() {}.type)
}
}
Note you want to use TypeToken not just T::class so if you read a List<YourType> you won't lose the type by type erasure.
With the type inference you can then use like this:
fun pricingData(): List<PricingData> = readRawJson(R.raw.mock_pricing_data)
Using:
String json_string = readRawResource(R.raw.json)
Functions:
public String readRawResource(@RawRes int res) {
return readStream(context.getResources().openRawResource(res));
}
private String readStream(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}