Kotlin JSON Processor using native Kotlin Serializable
@Serializer(forClass = DateSerializer ::class )
object DateSerializer : KSerializer<Date> {
override val descriptor: SerialDescriptor =
PrimitiveDescriptor (DateSerializer .javaClass.simpleName, PrimitiveKind .STRING )
override fun serialize (encoder : Encoder , value : Date ) {
encoder.encodeString(value.time.toString())
}
override fun deserialize (decoder : Decoder ): Date {
return Date (decoder.decodeString().toLong())
}
}
@Serializer(forClass = UUID ::class )
object UUIDSerializer : KSerializer<UUID> {
override val descriptor: SerialDescriptor
get() = StringDescriptor .withName(" UUID" )
override fun serialize (output : Encoder , obj : UUID ) {
output.encodeString(obj.toString())
}
override fun deserialize (input : Decoder ): UUID {
return UUID .fromString(input.decode())
}
}
@Serializable
open class Human (
@Serializable(with = UUIDSerializer ::class )
var uuid : UUID = UUID .randomUUID()
)
@Serializable
class User (val name : String , val age : Int ) : Human()
@Test
fun encodeDecodeHumanUser () {
val user = User (" Aerith Gainsborough" , 25 )
val encodedUserJson = JSON .stringify(User .serializer(), user)
val decodedUser = JSON .parse(User .serializer(), encodedUserJson)
Assert .assertEquals(user.name, decodedUser.name)
val id = UUID .randomUUID()
val validUserJson = " {\" id\" :\" $id \" ,\" name\" :${user.name} ,\" age\" :${user.age} }"
val decodedValidUser = JSON .parse(User .serializer(), validUserJson)
Assert .assertEquals(id.toString(), decodedValidUser.id.toString())
}