我已成功接收到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
}
我的控制台显示
表示未打印“用户创建”,因此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()))
}