对 Codec = Serialize / Deserialize 的 object 进行自动化的接口编解码处理 !
统一 API 使用.
JVM = 1.8+
一般应用在【通信协议层/配置数据层】的 class
对 String/byte[] field 转成你要的 interface/data class
最大的应用在于:
- 提供统一的自定义转换机制, 且可复用
- 提供手动触发的 API, 不黑箱
- 能够接入 interface/abstract class
这些 class, 一般是稳定的字段名, 改动往往是新开一个协议对象.
- CodecOrmApi
- SerializePreOrmApi 序列化
- DeserializePostOrmApi 反序列化
- 注解:
- @DeserializePostOrm
- @SerializePreOrm
- 工厂 API
- DeserializeOrmFactoryApi
- SerializeOrmFactoryApi
class DemoTestData : CodecOrmApi {
/**
* 反序列化来源的文本
*/
val text: String = """
{"name": "demo"}
""".trimIndent()
// 从哪个 field 反序列化 ?
@DeserializePostOrm(
fromFieldName = "text",
factoryClass = UserDeserializeFactoryApi::class
)
// 序列化到哪个 field ?
@SerializePreOrm(
toFieldName = "serializeText",
factoryClass = UserSerializeFactoryApi::class
)
var user: User? = null
var serializeText: String = ""
}
class UserDeserializeFactoryApi : DeserializeOrmFactoryApi<User> {
override fun type(): Class<User> {
return User::class.java
}
override fun deserializeFromText(text: String): User {
return Json.decodeFromString<User>(text)
}
override fun deserializeFromBytes(bytes: ByteArray): User {
return Json.decodeFromString<User>(String(bytes))
}
}
class UserSerializeFactoryApi : SerializeOrmFactoryApi<User> {
override fun type(): Class<User> {
return User::class.java
}
override fun serializeToText(obj: Any?): String? {
if (obj == null) {
return null
}
return Json.encodeToString(obj as User)
}
override fun serializeToBytes(obj: Any?): ByteArray? {
if (obj == null) {
return null
}
return Json.encodeToString(obj as User).encodeToByteArray()
}
}
class CodecOrmApiTest {
@Test
fun demo() {
val data = DemoTestData()
// deserialize
data.deserializePostOrm()
println(data.user!!.name)
// serialize
data.serializePreOrm()
println(data.serializeText)
}
}