How to parse JSON in Kotlin?
To parse JSON in Kotlin, you can use the JSONObject class from the org.json package.
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 JSONObjects and JSONArrays.
Here's an example of how you can parse a JSON string in Kotlin:
import org.json.JSONObject
import org.json.JSONException
fun main() {
val jsonString = """
{
"name": "John",
"age": 30,
"city": "New York"
}
"""
try {
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")
} catch (e: JSONException) {
println("Invalid JSON format: ${e.message}")
}
}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. The try-catch block handles potential JSONException errors if the JSON string is malformed.
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'For idiomatic Kotlin development, consider using kotlinx.serialization, which is specifically designed for Kotlin and offers better performance and type safety.