kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Unboxing null string values from JSON.

Open mandrachek opened this issue 3 years ago • 1 comments

I have an API that I'm dealing with that will return nulls encoded as a string "null", for example:

data model:

@Serializable
data class NullableString(val value: String? = null)

or

@Serializable
data class NullableOtherClass(val value: OtherSerializableObject? = null)

and in either case, the API may return

{ "value": "null" }
  1. Is there a way to provide a custom nullable serializer that will allow me to handle these myself? Just for strings, or for all object types?
  2. If so, is there a way to register this serializer to work with all Any? fields, rather than having to apply an annotation for every field?

If there is a solution for both 1&2, I'm good, however, if there is not, then I've got a problem (several thousand fields and growing in the data model for the API I'm dealing with).

I understand that this used to throw an error in lenient mode (#1600), and that making this the default behavior wouldn't be ideal for all use cases (e.g., German), but I would like to see a setting that perhaps works in conjunction with lenient mode, something like:

Json{ isLenient=true; unboxNullStrings = true }

Turning on that setting, if lenient mode is enabled, should allow:

  • null
  • "null"
  • 'null'

to all be treated as NULL for any nullable field during deserialization.

mandrachek avatar Jan 23 '22 17:01 mandrachek

I'll expand on this use-case somewhat; I'm dealing with an API that returns UUIDs as part of their JSON data, so I made a custom UUIDSerializer to handle those. However, aside from valid UUIDs and null, it also sometimes returns an empty string. Having some way to mark this as a null value would be great to have. Perhaps aside from throwMissingFieldException and throwArrayMissingFieldException we could have throwIsNullValueException?

Martmists-GH avatar May 19 '25 19:05 Martmists-GH