JSON Parsing (org.json)
import org.json.*Key Classes
Section titled “Key Classes”JSONArrayJSONObject
Parsing JSON
Section titled “Parsing JSON”- Pass a string with valid JSON format to
JSONArrayorJSONObject - Get a value of key with
jsonObject[<index>]orjsonObject.get<DataType> - To get a jsonObject in jsonObject use
.getJSONObject(<key>) - To get a jsonObject in jsonArray use
.getJSONObject(<index>)
Get data from a JSON object
Section titled “Get data from a JSON object”val jsonString = """ { "name": "Elias", "birthday": "2010-05-15", "favorite": "Coding" } """.trimIndent()
val jsonObject = JSONObject(jsonString)
val name = jsonObject.getString("name")val birthday = jsonObject.getString("birthday")val favorite = jsonObject.getString("favorite")
println("Name: $name")println("Birthday: $birthday")println("Favorite: $favorite")Get data from a JSON array
Section titled “Get data from a JSON array”val jsonString = """ { "name": "Elias", "hobbies": ["Coding", "Reading", "Writing"] } """.trimIndent()
val jsonObject = JSONObject(jsonString)
val name = jsonObject.getString("name")val hobbiesArray = jsonObject.getJSONArray("hobbies")
println("Name: $name")println("Hobbies:")
for (i in 0 until hobbiesArray.length()) { val hobby = hobbiesArray.getString(i) println("- $hobby")}Create JSON object or array
Section titled “Create JSON object or array”val name = "Elias"val age = 14val hobbies = listOf("Coding", "Reading", "Gaming")
// Create a JSON array from the hobbies listval hobbiesJsonArray = JSONArray()for (hobby in hobbies) { hobbiesJsonArray.put(hobby)}
// Create the JSON object and put data into itval jsonObject = JSONObject()jsonObject.put("name", name)jsonObject.put("age", age)jsonObject.put("hobbies", hobbiesJsonArray)
// Output the final JSON stringprintln(jsonObject.toString(2)) // Pretty print with 2 spaces