Hello is it possible to have a serializable data c...
# serialization
a
Hello is it possible to have a serializable data class with a field of type
N: Number
? Getting the following error:
Copy code
Serializer has not been found for type 'Number'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
k
I suggest annotating
data
with its own
@Serializable(with = …)
annotation. See the docs for examples:
Copy code
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>>
a
@kevin.cianfarini Could you link the doc you used to create a
KSerializer
for
Collection<N: Number>
? I see an example for
Box<T>
but in my case it's a collection so it's a bit different
k
Does it need to be a collection, or can it be a list?
ListSerializer
exists.
a
It could be a list, let me try that, thanks
Ok after an hour of trying differenet things it turns out that In my case I do not need to write a custom KSerializer for my data classes or for my
List<Number>
but I can instead leverage the fact that Kotlinx serialization support writing custom serializers for built-in types. Here is what ChatGPT found :
This approach was completely different than my approach and is much simpler and it works! I have to modify the code slightly for my need but 95% of it stayed the same! Now I can use this custom serializer for any place that requires a generic type of
N: 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
🙂