You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
privateval json =Json { encodeDefaults =true }
@Serializable
privatedata classPerson(
valname:Optional<String> = Optional.NotPresent,
valage:Optional<Int> = Optional.NotPresent,
valnested:Optional<Person?> = Optional.NotPresent,
)
@Test
fun`should not serialize absent values`() {
// Givenval person =Person(
name =Optional.NotPresent,
age =Optional.NotPresent,
nested =Optional.NotPresent,
)
// Whenval actualJsonString = json.encodeToString(person)
// Then
actualJsonString shouldBe "{}"
}
I get: Expected :"{}", Actual :"{"name":,"age":,"nested":}"
Expected behavior
The behaviour I would expect would be for the string to be just {}.
It works when I set encodeDefault = false, but for other serialization cases I need it to be true.
Environment
Kotlin version: 2.1.10
Library version: 1.6.0
Kotlin platforms: JVM
Gradle version: 8.6
The text was updated successfully, but these errors were encountered:
@MartinStigen Unfortunately it is not valid for (custom) serializers to serialize nothing. In the case of Json you're lucky the format actually produces something, but fundamentally the issue is with the serializer. If a value should be omitted this needs to be done before the serializer is called for the value (as the key/element name is separate and already written by that time). Have a look at how TagEncoder.encodeSerializableElement works through using TagEncoder.encodeElement to determine whether the element should be writen.
What you can do is have it serialize null and then using the settings omit the writing of null attributes. Otherwise you will need a custom serializer on the owner of the optionals, or use the @EncodeDefault annotation on the property to override the format. For the inline value you can then make this work regardless.
The whole framework is structured in a way that only the outer class (Person) serializer can decide whether to include its properties (name, age, ...) or not. You cannot decide this with the serializer for property type (OptionalSerializer). So if you want some custom logic to include or exclude properties, you have to write a PersonSerializer. However, in your case, it will be much easier to use the @EncodeDefault(NEVER) annotation if you don't want to change the state of the global flag.
Describe the bug
I am trying to create a wrapper class
Optional<T>
that can be used in type-safe patch requests:To Reproduce
But when I test this:
I get:
Expected :"{}", Actual :"{"name":,"age":,"nested":}"
Expected behavior
The behaviour I would expect would be for the string to be just
{}
.It works when I set
encodeDefault = false
, but for other serialization cases I need it to be true.Environment
The text was updated successfully, but these errors were encountered: