使用 kotlinx.serialization 多态性,我想得到
{"type":"veh_t","owner":"Ivan","bodyType":"cistern","carryingCapacityInTons":5,"detachable":false}
但我明白了
{"type":"kotlin.collections.LinkedHashMap","owner":"Ivan","bodyType":"cistern","carryingCapacityInTons":5,"detachable":false}
我使用以下型号
interface Vehicle {
val owner: String
}
@Serializable
@SerialName("veh_p")
data class PassengerCar(
override val owner: String,
val numberOfSeats: Int
) : Vehicle
@Serializable
@SerialName("veh_t")
data class Truck(
override val owner: String,
val body: Body
) : Vehicle {
@Serializable
data class Body(
val bodyType: String,
val carryingCapacityInTons: Int,
val detachable: Boolean
//a lot of other fields
)
}
我应用以下Json
inline val VehicleJson: Json get() = Json(context = SerializersModule {
polymorphic(Vehicle::class) {
PassengerCar::class with PassengerCar.serializer()
Truck::class with TruckKSerializer
}
})
我使用序列化器 TruckKSerializer 因为服务器采用扁平结构。同时,在应用程序中我想使用一个对象 Truck.Body。对于扁平化,我根据这些类中的文档使用 JsonOutput 和 JsonInput覆盖fun serialize(encoder: Encoder, obj : T)
和在 Serializator 中。fun deserialize(decoder: Decoder): T
object TruckKSerializer : KSerializer<Truck> {
override val descriptor: SerialDescriptor = SerialClassDescImpl("Truck")
override fun serialize(encoder: Encoder, obj: Truck) {
val output = encoder as? JsonOutput ?: throw SerializationException("This class can be saved only by Json")
output.encodeJson(json {
obj::owner.name to obj.owner
encoder.json.toJson(Truck.Body.serializer(), obj.body)
.jsonObject.content
.forEach { (name, value) ->
name to value
}
})
}
@ImplicitReflectionSerializer
override fun deserialize(decoder: Decoder): Truck {
val input = decoder as? JsonInput
?: throw SerializationException("This class can be loaded only by Json")
val tree = input.decodeJson() as? JsonObject
?: throw SerializationException("Expected JsonObject")
return Truck(
tree.getPrimitive("owner").content,
VehicleJson.fromJson<Truck.Body>(tree)
)
}
}
最后,我使用stringify(serializer: SerializationStrategy<T>, obj: T)
VehicleJson.stringify(
PolymorphicSerializer(Vehicle::class),
Truck(
owner = "Ivan",
body = Truck.Body(
bodyType = "cistern",
carryingCapacityInTons = 5,
detachable = false
)
)
)
我最终得到{"type":"kotlin.collections.LinkedHashMap", ...}
,但我需要{"type":"veh_t", ...}
如何获得正确的类型?我想使用多态性Vehicle
并使用 Truck.Body.serializer() 对 Body 对象进行编码以展平。
通过这种序列化,PassengerCar 类运行良好。
VehicleJson.stringify(
PolymorphicSerializer(Vehicle::class),
PassengerCar(
owner = "Oleg",
numberOfSeats = 4
)
)
结果正确:
{"type":"veh_p","owner":"Oleg","numberOfSeats":4}
我认为问题在于自定义序列化程序TruckKSerializer
。我注意到如果我在覆盖的fun serialize(encoder: Encoder, obj : T)
下一个代码中使用
encoder
.beginStructure(descriptor)
.apply {
//...
}
.endStructure(descriptor)
我得到了正确的类型,但无法使用它的序列化程序展平对象 Truck.Body。