Thoughts on more explicit Json serialization: ```c...
# codereview
d
Thoughts on more explicit Json serialization:
Copy code
class Example(
    name: String,
    age: Int? = null,
) : JsonObjectBuilder() {
    var name by required(name)
    var age by optional<Int>(age, includeNulls = true)
    val favoriteNumbers by optionalList<Int>()
}


fun main() {
    val value = Example("John")
    println(encodeToString(value)) 
    // {"name":"John"}
    value.age = 42
    value.favoriteNumbers.add(1)
    value.favoriteNumbers.add(2)
    println(encodeToString(value)) 
    // {"name":"John","age":42,"favoriteNumbers":[1,2]}
}
(This is utilizing kotlinx serialization under the hood, but I don't like how its interacting with it yet)
Problem statement: I am making an API request to a third party where the request body has many optional fields that don't need to always be sent. Some of the fields null doesn't mean default, but missing does. Not the best design, but its what exists. I'd like to create a DTO that will serialize only required fields or those that have been updated after instantiation.
j
If you use the proper defaults in your class, kotlinx serialization will not serialize default values
But it doesn't make a difference if you explicitly set a value to its default, which is something to keep in mind
d
Right, that was the problem I encountered.
f
Why not just use generated serializer
@Serializable
class Example(
name: String,
age: Int? = null,
)
d
@Fergus Hewson because I want to support:
Copy code
value.age = null
causing
Copy code
{"name":"John,"age": null}
f
The server requires null to be sent?
d
Sometimes
f
Copy code
@EncodeDefault(EncodeDefault.Mode.ALWAYS) age: Int? = null
d
Because I don't want it encoded unless it was changed.
There are also a few Union types. (null|string|array[]), so having more direct control over the json form would be helpful.
f
Have you looked into polymorphic type adaptation?
d
I did briefly.
a
Don’t the serializer options allow you to add nulls?