I'm trying to map enum to int values: ```@Serializ...
# serialization
p
I'm trying to map enum to int values:
Copy code
@Serializable
enum class ItemType {
    @SerialName("0") Zero,
    @SerialName("1") First,
}
But it fails with the following exception:
Copy code
JsonDecodingException: Unexpected JSON token at offset 194: Expected quotation mark '"', but had '1' instead
    JSON input: ....."type":1,.....
It doesn't seem to work because
SerialName
is expecting a string and json has an int. I can think of two ways to solve this: 1. Enabling lenient mode - I don't like this solution as it also removes restrictions from other fields, which I prefer to keep 2. Implementing a custom serializer - seems like too much of boilerplate code for such a simple task Am I missing something?
a
hi, I think those are your two options. and I think a custom serializer is the best one. It wouldn't be very much boilerplate, see Json transformations. Do you have some example JSON?
here's a demo that serializes
ItemType
to/from an integer. It uses
requireNotNull(...)
to verify the ItemType is known. And personally I prefer hardcoding the ID of an enum, rather than relying on
.ordinal
- but you can do that too. If you wanted to do this for lots of enums, that's possible too. You'd have to make your own annotation and mark it as
@SerialInfo
. Then write a single 'enum-as-int serializer', which would be used for all required enums.
p
@Adam S Thanks, the custom annotation option seems interesting to me, I haven't used
SerialInfo
before, could you give me a link to an example or documentation? I have not been able to find it on my own.
a
I can't really think of a good way to get
@SerialInfo
to work actually. It gets a bit messy because the point of it is that the KXS plugin will generate a SerialDescriptor that includes the
@SerialInfo
annotation, but in this instance you'd need to write your own descriptor anyway...
probably the cleanest way to re-use an 'enum as int' serializer is to use an interface, like this.
p
@Adam S Thank you, that seems like the cleanest solution to me so far
👍 1
1114 Views