Alexandre Brown
02/28/2023, 6:15 PMN: Number
?
Getting the following error:
Serializer has not been found for type 'Number'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
kevin.cianfarini
02/28/2023, 6:19 PMdata
with its own @Serializable(with = …)
annotation. See the docs for examples:
For annotated properties, specifying with parameter is mandatory and can be used to override serializer on the use-site without affecting the rest of the usages:
@Serializable // By default is serialized as 3 byte components
class RgbPixel(val red: Short, val green: Short, val blue: Short)
@Serializable
class RgbExample(
@Serializable(with = RgbAsHexString::class) p1: RgpPixel, // Serialize as HEX string, e.g. #FFFF00
@Serializable(with = RgbAsSingleInt::class) p2: RgpPixel, // Serialize as single integer, e.g. 16711680
p3: RgpPixel // Serialize as 3 short components, e.g. { "red": 255, "green": 255, "blue": 0 }
)
In this example, each pixel will be serialized using different data representation.
For classes with generic type parameters, serializer() function requires one additional argument per each generic type parameter:
@Serializable
class Box<T>(value: T)
Box.serializer() // Doesn't compile
Box.serializer(Int.serializer()) // Returns serializer for Box<Int>
Box.serializer(Box.serializer(Int.serializer())) // Returns serializer for Box<Box<Int>>
Alexandre Brown
02/28/2023, 7:03 PMKSerializer
for Collection<N: Number>
?
I see an example for Box<T>
but in my case it's a collection so it's a bit differentkevin.cianfarini
02/28/2023, 7:06 PMListSerializer
exists.Alexandre Brown
02/28/2023, 7:06 PMAlexandre Brown
02/28/2023, 8:30 PMList<Number>
but I can instead leverage the fact that Kotlinx serialization support writing custom serializers for built-in types.
Here is what ChatGPT found :Alexandre Brown
02/28/2023, 8:31 PMN: Number
(list<N>, collection<N>, property of type N etc).
This just unblocked me after 1h of searching and testing things in the doc.
Thanks ChatGPT ❤️ and thanks @kevin.cianfarini
I'm amazed, I would have never tried the approach to use forClass
🙂