JSONElement Usage
The JsonElement class is the base class for all JSON elements in Kotlin. It represents a JSON value, which can be a JSON object, a JSON array, a JSON string, a JSON number, a JSON boolean, or JSON null.
JsonElementUtils provides utility functions for working with JsonElement objects.
Many of the JsonElement functions have a vararg String path argument. These arguments are used to navigate the JSON object hierarchy. A path can be either comma-separated strings or a single dot-separated string.
Simple JSONElement Example
  fun jsonElementExample() {
    val json = """
      {
        "person": {
          "first": "Bill",
          "last": "Lambert",
          "address": {
            "street": "123 Main",
            "city": "Tusla"
          }
        }
      }
    """
    // Convert the json string to a JsonElement
    val je: JsonElement = json.toJsonElement()
    println(je.keys) // [person]
    println(je["person"].keys) // [first, last, address]
    println(je["person.address"].keys) // [street, city]
    // Get the value of the "person.first" key using the stringValue extension property
    println(je["person.first"].stringValue) // Bill
    // Get the value of the "person.last" key using the stringValue extension function
    println(je.stringValue("person.last")) // Lambert
    // Get the value of the "person.address.street" key
    println(je.stringValue("person.address.street")) // 123 Main
    // Get the value of the "person.address.street" key using the get function and the vararg keys parameter
    println(je["person", "address", "city"].stringValue) // Tulsa
    println(je.toJsonString())
    /*
      Outputs:
      {
        "person": {
          "first": "Bill",
          "last": "Lambert",
          "address": {
            "street": "123 Main",
            "city": "Tusla"
          }
        }
      }
     */
  }
Last modified: 04 October 2024