Last active
February 15, 2021 14:11
-
-
Save abircse/6d0d8af258ee434bd87c8714fe2b7337 to your computer and use it in GitHub Desktop.
LocalJSONParserExtension
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
1. Create this BaseLocalJsonParser Compenion object | |
object BaseLocalJsonParser { | |
fun parseJSONData(context: Context, jsonFileName: String): String? { | |
val JSONString: String? | |
JSONString = try { | |
val inputStream: InputStream = context.assets.open(jsonFileName) | |
val sizeOfJSONFile: Int = inputStream.available() | |
val bytes = ByteArray(sizeOfJSONFile) | |
inputStream.read(bytes) | |
inputStream.close() | |
String(bytes, UTF_8) | |
} catch (ex: IOException) { | |
ex.printStackTrace() | |
return null | |
} | |
return JSONString | |
} | |
} | |
2. load json file from asset & set data to model with GSON | |
val gson = Gson() | |
var model: YourModelClass = gson.fromJson(BaseLocalJsonParser.parseJSONData(requireContext(), "filepathassetfolder/yourfile.json"), YourModelClass::class.java) | |
Enjoy :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment