https://kotlinlang.org logo
#serialization
Title
# serialization
d

Distractic

11/23/2023, 1:20 PM
Hello With Kotlin Serialization, I need to adapt a decode value. An API can return: • Valid value • Or empty string I would like to set my variable as
MyExpectedType?
(nullable) and the value must be null when the String is empty. Without modification into the custom serializer, is it possible to have this behavior ?
a

Adam S

11/23/2023, 6:47 PM
Are you dealing with JSON? Is the valid value also a string, or is it an object? (Some example data would help, can you share some?)
d

Distractic

11/23/2023, 6:48 PM
The valid value is a String parsed as Duration
• Invalid value: null / "" • Valid value: "1m", / "10d13d"
a

Adam S

11/23/2023, 10:50 PM
If you don't want to deal with a custom serializer then one easy way is to decode it as a string and define an additional property in the class, e.g.
val duration: Duration get() = ...
, and only convert it to a duration if the string isn't blank