Last active
May 9, 2025 10:36
-
-
Save aroranubhav/c2faa8ff6d3b6a03355fe37f63adacc1 to your computer and use it in GitHub Desktop.
Read Json File from Assets Folder and map it to a model class
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
| //This code snippet assumes the JSON file content is an array of MODEL_CLASS objects. | |
| var content = emptyArray<MODEL_CLASS>() | |
| fun readJsonFile(context: Context) { | |
| //get an input stream from assets folder for the file | |
| val inputStream = context.assets.open("FILE_NAME.json") | |
| //get input stream size | |
| val size: Int = inputStream.available() | |
| //create a byte array of corresponing size | |
| val buffer = ByteArray(size) | |
| //read it in form of bytes | |
| inputStream.read(buffer) | |
| //close the input stream | |
| inputStream.close() | |
| //convert byte array into string(json) | |
| val json = String(buffer, Charsets.UTF_8) | |
| //Gson for desrialization | |
| val gson = Gson() | |
| //convert json string into array of model objects | |
| content = gson.fromJson(json, Array<MODEL_CLASS>::class.java) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment