使用 Int 作为 Kotlin 数据类的参数
创建数据类时遇到一些问题。第一篇文章,有点菜鸟 - 温柔点:)
我正在尝试创建一个 Kotlin 数据类来处理我们使用的 API 的一些响应;其响应看起来有点像这样:
"data": {
"devices": {
"600": [
{
"device_id": "[deviceId]", ...
我遇到的麻烦是“600”位 - 我找不到一种方法来创建以此作为参数的数据类。每次我声明 var/val 时,它都会引发错误,但不会在 IDE 中提供任何有用的选项。其余的都是字符串,因此“devices”变成“val devices: String”等等。但在这种情况下 val 是一个 Int,我不知道如何在数据类中声明它。
我希望将 API 响应重新设计为更容易定义的内容,但这需要时间。谁能告诉我如何传递 Int 作为参数?
这是数据类:
data class SimRetrieveDevicesResponse(
val data: Devices,
val error: String? = null,
)
data class Devices(
val 600: List<DeviceInfo>? = null
)
data class DeviceInfo(
val device_id: String,
val device_type: String,
val network_id: String,
val send_period_sec: Int,
val loss_in_thousand: Int,
val tti_application_id: String,
val cmt_tenant_id: String,
)
抱歉,我把任何东西都叫错了名字......
got a bit of a problem with creating a data class. First post, and a bit of a noob - be gentle :)
I'm trying to create a Kotlin data class to handle some responses from an API we use; the response of which looks a bit like this:
"data": {
"devices": {
"600": [
{
"device_id": "[deviceId]", ...
What I'm having trouble with is the "600" bit - I can't find a way to create the data class with this as a parameter. Each time I declare the var/val - it's throwing an error, but doesn't provide any helpful options in the IDE. All the rest are strings, so "devices" becomes "val devices: String" and so on. But in this case the val is an Int, and I don't know how to declare this in the data class.
I want to have the API response re-worked to something more easily defined, but that'll take time. Can anyone tell me how I can pass the Int as the parameter?
This is the data class:
data class SimRetrieveDevicesResponse(
val data: Devices,
val error: String? = null,
)
data class Devices(
val 600: List<DeviceInfo>? = null
)
data class DeviceInfo(
val device_id: String,
val device_type: String,
val network_id: String,
val send_period_sec: Int,
val loss_in_thousand: Int,
val tti_application_id: String,
val cmt_tenant_id: String,
)
Sorry I've called anything the wrong name...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反引号 val 修复了错误,并且有很大帮助。
Backtick-ing the val has fixed the error, and helped tremendously.
正如评论中所述,映射很可能是地图,因此拥有名为“600”的属性(无论是否反勾)都是不正确的。一旦您有另一个值(例如“700”),您就必须更改代码。
这是一个可行的解决方案,基于 JSON 片段中的假设,即设备是设备信息列表的映射:
此处的断言使用 kotest,您可以通过在 build.gradle.kts 中添加它
As stated in the comments, the mapping is more than likely for a map, so having a property called "600", back-ticked or not, is incorrect. As soon as you have another value like "700", you'd have to change your code.
Here's a working solution, based on the assumption from your JSON snippet that devices is a map of a list of device information:
The assertions here use kotest, which you can add via this in your build.gradle.kts