the property will be serialized if it’s found in JSON, else the serialized object will have age as null, unlike for required objects where a MissingFieldException is thrown. In our case, age is an optional property with null as its default value. You don’t need to do anything special to handle optional values when working with Kotlin serialization.Īll properties with default values are considered optional. Kotlin’s features - especially its nullable types and default parameter values prove to be great when dealing with JSON. (You can see all these examples as a series of unit tests here in this gist ) Handling optional values data class User( val id: String, val name: String, val age: Int? = null ) Ktorm's preferred method is to use interfaces extending which implements Serializable. Let’s consider we updated out User data object to contain a required, non-nullable and unique id and age, which is an optional, nullable property. If rialization would support classes that implement the java.io.Serializable interface instead of just serializable annotated classes, I could use the same class for rialization and for Ktorm. These properties might or might not be present at runtime. When interacting with a Rest API, it’s common to have some optional properties in the response. Kotlin serialization - Optional and transient properties
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |