Last active
August 25, 2022 11:54
-
-
Save rommansabbir/6d7304c8cc348b8aa8eaae6d95c23c8c to your computer and use it in GitHub Desktop.
Android: Load JSON from `src/main/assets/`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Android: Load JSON from `src/main/assets/` */ | |
/* Extension function where `Context` passed explicitly */ | |
fun loadJSONFromAsset(context: Context, fileName: String): String { | |
val inputStream: InputStream = context.assets.open(fileName) | |
val size: Int = inputStream.available() | |
val buffer = ByteArray(size) | |
inputStream.read(buffer) | |
inputStream.close() | |
return String(buffer, Charset.defaultCharset()) | |
} | |
/* Extension function of `Context` class */ | |
fun Context.loadJSONFromAsset(fileName: String): String { | |
val inputStream: InputStream = this.assets.open(fileName) | |
val size: Int = inputStream.available() | |
val buffer = ByteArray(size) | |
inputStream.read(buffer) | |
inputStream.close() | |
return String(buffer, Charset.defaultCharset()) | |
} | |
/* Usages */ | |
loadJSONFromAsset(context,"mock_response.json") | |
/* Alternative */ | |
context.assets.open(fileName).bufferedReader().use(JsonParser::parseReader).asJsonObject.toString() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment