JSON parsing in Android
Overview
JSON parsing is used to read JSON file from a .json file. To parse the data we have to use a library GSON.
Steps to follow
- Add the required dependency in build.gradle (Module) file.
// GSON
def gson_version = "2.8.6"
implementation "com.google.code.gson:gson:$gson_version"
- Parse the .json data with the help of following code
private fun loadQuotesFromAssets(): Array<Quote> {
val inputStream = context.assets.open("quotes.db")
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
val json = String(buffer, Charsets.UTF_8)
val gson = Gson()
return gson.fromJson(json, Array<Quote>::class.java)
}
Comments
Post a Comment