-
Notifications
You must be signed in to change notification settings - Fork 645
Delegate to default Serializer #1253
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Related: #1169 Btw, in your case It is worth looking into json transformers rather than full-blown custom serializers |
How can I return null? public object ProgramSerializer : JsonTransformingSerializer<Program>(Program.serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement =
if (element is JsonObject) {
element
} else {
null
}
} @Serializable
public data class SomeObject(
@Serializable(with = ProgramSerializer::class)
val program: Program? = null,
) I tried returning
|
Hello? |
Unfortunately, |
a temporary solution if you only need to deserialize, you can copy the logic from abstract class NullableJsonTransformingSerializer<T : Any>(
private val tSerializer: KSerializer<T>
) : KSerializer<T?> {
override val descriptor: SerialDescriptor get() = tSerializer.descriptor
final override fun deserialize(decoder: Decoder): T? {
require(decoder is JsonDecoder)
val element = decoder.decodeJsonElement()
return nullableTransformDeserialize(element)?.let { decoder.json.decodeFromJsonElement(tSerializer, it) }
}
protected open fun nullableTransformDeserialize(element: JsonElement): JsonElement? = element
final override fun serialize(encoder: Encoder, value: T?) {
throw IllegalAccessError("serialize not supported")
}
} unfortunately |
Hi there, I'm running into the same use case. Are there any plans to support nullable types with The only way I can see around this for the time being (when serialization is also required, otherwise @ouchadam 's solution should work) is to replace the nullable type with a non-null one, and use a special Thank you! |
I think nullable JsonTransformingSerializer is a separate issue, can you please create one? |
Fixed by #1169 |
Hi,
I'm dealing with an annoying
JSON
service which is out of my control.If a value is unavailable it is expressed as an empty array
[]
instead of a canonical absence ornull
value.I thought about making a custom
JSON
deserialiser and manually check if the value was present or not before delegating it to the default generated deserialiser.However when defining a custom deserialiser it seems the generated deserialiser is not generated no more.
I made a simple test case here:
Note that this example is a simple use case.
As a temporary solution I made a copy of my object without specifying the custom deserialiser which I reference in my own deserialiser and then map back to my original object.
However that of course does not seem to be a good solution.
The text was updated successfully, but these errors were encountered: