如何在Kotlin中将数据类转换为ByteBuffer? [英] How to convert a Data Class to ByteBuffer in Kotlin?
问题描述
我正在尝试使用Kinesis,它需要字节缓冲区格式的数据.到目前为止,我所看到的所有示例都是使用Java并传递简单的字符串. 有人可以提出如何将Kotlin数据类转换为字节缓冲区的想法吗?
I am trying to use Kinesis, which expects data in byte buffer format. All the examples I have seen so far are in Java and pass simple strings. Can anybody give an idea of how to convert a kotlin data class to bytebuffer?
例如 数据类abc( var a:长, var b:字符串, var c:Double )
e.g. data class abc ( var a: Long, var b: String, var c: Double )
推荐答案
感谢所有建议.
使用杰克逊库(jackson-databind)和注解的ObjectMapper()解决了该问题. 以下代码用于序列化:
Solved the problem using ObjectMapper() of Jackson library (jackson-databind) and annotations. Following code used for serialization:
val objectMapper = ObjectMapper()
objectMapper.registerModule(JavaTimeModule())
val buf = ByteBuffer.wrap(objectMapper.writeValueAsString(className).toByteArray(Charsets.UTF_8))
反序列化代码:
val objectMapper = ObjectMapper()
objectMapper.registerModule(JavaTimeModule())
val obj = objectMapper.readValue(Charsets.UTF_8.decode(record.data()).toString(), ClassName::class.java)
除此之外,我必须添加所有数据类的构造函数,并且必须将以下注释添加到所有LocalDateTime属性:
Apart from this, I had to add constructors of all the data classes and had to add the following annotation to all the LocalDateTime attributes:
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
var edd: LocalDateTime?,
这篇关于如何在Kotlin中将数据类转换为ByteBuffer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!