Skip to content
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

CBOR serializer encodes null class instance as empty map instead of null #2848

Open
Jacob-Amazon opened this issue Nov 5, 2024 · 2 comments

Comments

@Jacob-Amazon
Copy link

Traced to this line:

I consider this a bug. Null objects should be encoded as the simple type null, no matter whether they are class types or other types.

In our use case, this is causing issues after deserialization, since the empty map is deserialized into a default instance of the type, rather than null.

Please consider removing this line and always encoding as null.

@sandwwraith
Copy link
Member

Can you please provide an example of serializable class and expected/actual output?

@Jacob-Amazon
Copy link
Author

@Serializable
data class Test(val nullableClass: Inner?, val nullableMap: Map<String, String>?)

@Serializable
data class Inner(val test: Int)

val test = Test(nullableClass = null, nullableMap = null)
Cbor.encodeToByteArray(Test.serializer(), test)
// Hex output: bf6d6e756c6c61626c65436c617373a06b6e756c6c61626c654d6170f6ff

The hex output bf6d6e756c6c61626c65436c617373a06b6e756c6c61626c654d6170f6ff looks like this (from https://cbor.me/):

{ "nullableClass": {}, "nullableMap": null}
BF                               # map(*)
   6D                            # text(13)
      6E756C6C61626C65436C617373 # "nullableClass"
   A0                            # map(0)
   6B                            # text(11)
      6E756C6C61626C654D6170     # "nullableMap"
   F6                            # primitive(22)
   FF                            # primitive(*)

Expected output would be this: bf6d6e756c6c61626c65436c617373f66b6e756c6c61626c654d6170f6ff

{ "nullableClass": null, "nullableMap": null}
BF                               # map(*)
   6D                            # text(13)
      6E756C6C61626C65436C617373 # "nullableClass"
   F6                            # primitive(22)
   6B                            # text(11)
      6E756C6C61626C654D6170     # "nullableMap"
   F6                            # primitive(22)
   FF                            # primitive(*)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants