Skip to content

Instantly share code, notes, and snippets.

@delacrixmorgan
Last active April 27, 2020 08:25
Show Gist options
  • Save delacrixmorgan/a8dc9a30061f16db3e743a4fe7dbe988 to your computer and use it in GitHub Desktop.
Save delacrixmorgan/a8dc9a30061f16db3e743a4fe7dbe988 to your computer and use it in GitHub Desktop.
Kotlin JSON Processor using native Kotlin Serializable

Kotlin JSON Processor using native Kotlin Serializable

Date Serializer

@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())
    }
}

UUID Serializer

@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())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment