Skip to content

Instantly share code, notes, and snippets.

@abircse
Last active February 15, 2021 14:11
Show Gist options
  • Save abircse/6d0d8af258ee434bd87c8714fe2b7337 to your computer and use it in GitHub Desktop.
Save abircse/6d0d8af258ee434bd87c8714fe2b7337 to your computer and use it in GitHub Desktop.
LocalJSONParserExtension
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