gpt4 book ai didi

json - Kotlin:来自Json的GSON无法计算

转载 作者:行者123 更新时间:2023-12-02 13:44:40 26 4
gpt4 key购买 nike

我已成功接收到JSON对象作为请求并将其传递给解析器。代码一直运行到我从Json调用,然后卡住为止。我究竟做错了什么?

这是相应的类:

class User(@SerializedName("mac") private val phoneMac: String) : Comparable<User> {

@SerializedName("values")
private val measurements: MutableSet<Measurement> = mutableSetOf()

fun getPhoneMac(): String = phoneMac
fun getMeasurements(): Set<Measurement> = measurements

//etc.
}

指的是此类:
class Measurement (@SerializedName("mac") val deviceMac: String, val timestamp: String, val value: Double, val valueType: ValueType) : Comparable<Measurement>{

fun getDeviceMac(): String = deviceMac
fun getTimestamp(): String = timestamp
fun getValue(): Double = value
fun getValueType(): ValueType = valueType

//etc.
}

这是我尝试解析的方法:
fun fromJson(json: String): User {
val builder = GsonBuilder()
builder.setPrettyPrinting()

return builder.create().fromJson(json, User::class.java)
}

是否已将fromJson函数展开以确保其卡在哪里:create()仍然有效,fromJson()不起作用

另外,我知道JSON文件是正确的,并且不包含缺失值或null。

进行验证:
{
"mac": "00-80-41-ae-fd-b1",
"values":
[
{
"mac": "ab-cd-ef-98-76-13",
"timestamp": "2012-04-23T18:25:43",
"value": 68,
"valuetype": "HR"
},
{
"mac": "ab-cd-ef-98-76-13",
"timestamp": "2012-04-23T18:35:43",
"value": 65,
"valuetype": "HR"
}
]
}

编辑:澄清我的代码被卡住的意思
出于调试目的,我将fromJson函数更改为如下所示:
fun fromJson(json: String): User {
val builder = GsonBuilder()
builder.setPrettyPrinting()

println("json received")
val gson = builder.create()
println("GSON created")
val user = gson.fromJson(json, User::class.java)
println("user created")

return user
}

我的控制台显示

json received GSON created



表示未打印“用户创建”,因此gson.fromJson-call永不返回

最佳答案

不确定卡住是什么意思,但这似乎奏效:

import com.google.gson.*
import com.google.gson.annotations.*

data class User(@SerializedName("mac") val phoneMac: String, @SerializedName("values") val measurements: MutableSet<Measurement>)

enum class ValueType{
HR
}

data class Measurement (@SerializedName("mac") val deviceMac: String, val timestamp: String, val value: Double, val valuetype: ValueType)

fun fromJson(json: String): User {
val builder = GsonBuilder()
builder.setPrettyPrinting()

return builder.create().fromJson(json, User::class.java)
}

fun main() {
println(fromJson("""
{
"mac": "00-80-41-ae-fd-b1",
"values":
[
{
"mac": "ab-cd-ef-98-76-13",
"timestamp": "2012-04-23T18:25:43",
"value": 68,
"valuetype": "HR"
},
{
"mac": "ab-cd-ef-98-76-13",
"timestamp": "2012-04-23T18:35:43",
"value": 65,
"valuetype": "HR"
}
]
}
""".trimIndent()))
}

关于json - Kotlin:来自Json的GSON无法计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59932663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com