有没有一种方法可以将JSON逐渐化为Kotlin数据类并转换属性类型?
我当前有一些JSON
{
"name": "Foo",
"age": 12,
"id": "1234567890"
}
,我的数据类,我希望将其归类为看起来像是
data class Example( val name: String, val age: Int, val id: String)
有一种方法可以将数据类简单地将
data class Example( val name: String, val age: Int, val id: Long)
关注ID类型long
关注这可以通过使用将数据类解析为单独的数据类的扩展功能来实现。
但是我想知道这是否可以以其他方式进行。我正在使用杰克逊进行审判。
I have some json
{
"name": "Foo",
"age": 12,
"id": "1234567890"
}
Currently, my data class I want to deserialize into looks like this
data class Example( val name: String, val age: Int, val id: String)
Is there a way to simply have the data class as
data class Example( val name: String, val age: Int, val id: Long)
Attention to the id type Long
I suppose this can be achieved through the use of an extension function that parses the data class into a separate data classes.
But I'd like to know if this is possible in any other way. I'm using Jackson for deserialization.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不必做任何事情。如果可能的话,杰克逊会自动将字符串转换为长时间:
此自动转换由 mapperfeature.allow_coercion_of_scalars ,默认启用。
You don't have to do anything. Jackson automatically converts the String into a Long if it is possible:
This automatic conversion is controlled by MapperFeature.ALLOW_COERCION_OF_SCALARS, which is enabled by default.
我知道您说您正在使用杰克逊,但是Kotlin现在有本机对序列化的支持!。使用它,您的代码看起来像这样。
您也可以查看此示例来自官方文档
I know you said you're using jackson, but Kotlin now has native support for serialization!. Using that, your code would look like this
You can also check out this example from the official docs