Parsing a JSON response using Gson
In this recipe, we will learn how to parse JSON. JSON is the most widely used data type for API responses. We will be using Gson, an open source library by Google. It's fast, and it scales very well even with a huge response.
Getting ready
I'll be using Android Studio for this purpose, and JSONObject is provided by Android SDK. We will be using Gson for JSON parsing. You can add it to your project by adding the following lines to your build.gradle
file:
compile 'com.google.code.gson:gson:2.8.0'
How to do it…
Now, let's follow these steps to parse JSON data using Gson. For example, we will use a raw string here to keep things simple:
- First, we will create dummy JSON data using a raw string, as follows:
val jsonStr=""" { "name": "Aanand Shekhar", "age": 21, "isAwesome": true } """.trimIndent()
- Next, we will create a data class to hold this data. Here's how our data class looks:
data class Information(val name:String,val age:Int, val isAwesome...