How to parse JSON in Kotlin?
To parse JSON in Kotlin, you can use the JSONObject
class from the org.json
package. This class provides methods for parsing JSON strings and converting them to JSONObject
s and JSONArray
s.
Here's an example of how you can parse a JSON string in Kotlin:
import org.json.JSONObject
fun main() {
val jsonString = """
{
"name": "John",
"age": 30,
"city": "New York"
}
"""
val json = JSONObject(jsonString)
val name = json.getString("name")
val age = json.getInt("age")
val city = json.getString("city")
println("Name: $name")
println("Age: $age")
println("City: $city")
}
This code creates a JSON string and then uses the JSONObject
class to parse it. It gets the values of the "name", "age", and "city" fields using the getString
and getInt
methods, and prints them to the console.
You can also use the getJSONArray
method to parse JSON arrays and the getJSONObject
method to parse nested JSON objects.
Note that the JSONObject
class is part of the org.json library, which is not included in the standard Kotlin library. You will need to include the org.json library in your project in order to use the JSONObject
class. You can do this by adding the following dependency to your build.gradle file:
implementation 'org.json:json:20210020'