Add Serializer
This commit is contained in:
16
src/main/kotlin/fr/postgresjson/entity/Entity.kt
Normal file
16
src/main/kotlin/fr/postgresjson/entity/Entity.kt
Normal file
@@ -0,0 +1,16 @@
|
||||
package fr.postgresjson.entity
|
||||
|
||||
import java.util.*
|
||||
|
||||
interface EntityI<T> {
|
||||
var id: T
|
||||
}
|
||||
abstract class Entity<T>(override var id: T) : EntityI<T>
|
||||
abstract class UuidEntity(override var id: UUID = UUID.randomUUID()) : Entity<UUID>(id) {}
|
||||
abstract class IdEntity(override var id: Int) : Entity<Int>(id)
|
||||
|
||||
interface EntityVersioning<T> {
|
||||
var version: T
|
||||
}
|
||||
|
||||
interface EntityVersioningIncrement : EntityVersioning<Int>
|
||||
23
src/main/kotlin/fr/postgresjson/serializer/Serializer.kt
Normal file
23
src/main/kotlin/fr/postgresjson/serializer/Serializer.kt
Normal file
@@ -0,0 +1,23 @@
|
||||
package fr.postgresjson.serializer
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.readValue
|
||||
import fr.postgresjson.entity.Entity
|
||||
|
||||
class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
|
||||
fun serialize(source: Any): String {
|
||||
return mapper.writeValueAsString(source)
|
||||
}
|
||||
|
||||
inline fun <reified T>deserialize(json: String): T {
|
||||
return mapper.readValue(json)
|
||||
}
|
||||
|
||||
inline fun <reified T>deserialize(json: String, target: T): T {
|
||||
return mapper.readerForUpdating(target).readValue(json)
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> Entity<T>.serialize() = Serializer().serialize(this)
|
||||
inline fun <reified T> T.deserialize(json: String) = Serializer().deserialize(json, this)
|
||||
Reference in New Issue
Block a user