-
Notifications
You must be signed in to change notification settings - Fork 99
Adds the option to encode enums as 1-key maps. #67
Conversation
This would indeed be very useful to have, I also have a use case that would be much easier to support from a Go serializer with something like this PR is proposing. Are there any design decisions needed, can anyone review? |
Sorry. I missed this. I will review this week. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried to use the code from this PR and there are a few issues that need to be fixed:
- Unit variants are still serialized as string/int even if
enum_as_map
is set. To be consistent, they should be serialized as maps as well, e.g.,{"Foo": {}}
as otherwise deserialization in a different language needs to deal with a special case where the value is a string/int instead of a struct which is annoying. - Struct variants are still serialized as 2-length lists even if
enum_as_map
is set.
These are trivial to fix and I've fixed them in my branch - I can push my changes if needed. Otherwise the code seems to work well.
Please create a PR. |
So for my first point, actually it seems that |
I think if we add this the serialization should match the one used by serde-json. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Needs some tests. With the comments addressed it is fine.
Tests added. I've also added a |
Adds SerializerOptions::to_vec. Removes to_vec_with_options_sd.
e2b9acf
to
5523707
Compare
@ogoodman thanks for taking the time to update this, I just got back from vacation and didn't have time to push my changes before. I did a cursory look over the new changes and it seems ok. Regarding option defaults, either the |
@kostko thanks for your comments. Sorry if I caused you to waste time working on this. I didn't think I'd have time to work on it for a while, but then I unexpectedly did. |
Thank you @ogoodman 👍 |
Since enums are part of the Rust language but not part of the CBOR or JSON spec, each serializer has to make a choice how to encode them.
serde_cbor chose
["Variant", items..]
while serde_json chose{"Variant": item}
or{"Variant": [items..]}
. Although this is immaterial when passing data between Rust programs, it becomes visible ifValues
are used, or when data is passed between Rust and other languages.This turned out to be a problem for me when I tried to migrate a communicating pair of Python and Rust programs from JSON to CBOR, as assumptions about the encoding of enums had already become buried throughout the Python code.
This pull request adds the option (default false) to encode enums in the serde_json way and adds support for automatically decoding enums from either encoding.