gertix.blogg.se

Kotlin any
Kotlin any







kotlin any kotlin any

If you're sure about the order of properties in your serialization format/message (or just feel lucky) you may go with the following custom serializer: import rialization.* It could happen that payload is about to be deserialized before dataType, and Decoder interface doesn't allow to go back/make several passes. Some serialization formats (like JSON or Protobuf) have unordered schema. Serialization of Any could be handled (for declared list of its subclasses), but dynamic determintaion of deserialization strategy based on dataType field of partly deseriazed object is impossible in general case, because there is no guarantee that dataType field will be deserialized first. In rialization each class can have its own serialization strategy (or even several ones). This is because java serialization is rather primitive - there is only one way to serialize (and hence to deserialize) an object. The framework won't ignore the payload: Any field (gives a compile error) and I can't even write a custom serializer because defining an element of type Any in a customer serializer (for the descriptor) gives the same run-time error of "no serializer registered for Any." In the docs they recommend a polymorphic approach, which sorta works but you have to make the packet typed: data class Packet(val dataType: String, val payload: T) : SomeBaseClassīut this kinda sucks because it weighs down a lot of code paths with inline reified typing, plus this doesn't solve that the receiving end won't know what type to try to deserialize the payload as without being to look at the dataType field first. Easy breazy.īut Kotlinx Serialization (with ProtoBuf) is a stickler about this Any type for reasons that aren't obvious to me. The receiver can't know the type of the payload but Java deserializes it just fine, and then I use when(dataType) as a lookup to correctly cast the Any object to its correct type. I've used Java serialization to send it over the wire. class Packet(val dataType: String, val payload: Any)

kotlin any

I have a class that gets serialized for network traffic.









Kotlin any