Kotlin/Kotlinx - Changed kotlinx anytype from JsonObject to JsonElement
In #1339 the any type for the kotlinx generation was changed to JsonObject which I have personally found to cause more issues than it solves. Often when generating kotlin code for json examples with nulled attributes the kotlinx generator outputs these as JsonObjects only for deserialisation to later fail when the attributes are present as an array or a primitive.
This PR replaces JsonObject for the any type with its parent class JsonElement - this allows the attribute to take on not only object types, but arrays and primitives as well. It keeps the JsonArray and JsonObject for arrayType and mapType respectively.
Example of the change in action:
Input:
echo '{"name":null}' | ./script/quicktype --lang kotlin --top-level Person --framework kotlinx
Before:
// To parse the JSON, install kotlin's serialization plugin and do:
//
// val json = Json { allowStructuredMapKeys = true }
// val person = json.parse(Person.serializer(), jsonString)
package quicktype
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
@Serializable
data class Person (
val name: JsonObject? = null
)
After:
// To parse the JSON, install kotlin's serialization plugin and do:
//
// val json = Json { allowStructuredMapKeys = true }
// val person = json.parse(Person.serializer(), jsonString)
package quicktype
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
@Serializable
data class Person (
val name: JsonElement? = null
)
The original output will fail to parse a payload such as {"name":"John Smith"}