jackson kotlin-无法从START_OBJECT令牌中反序列化`java.util.ArrayList`的实例 [英] jackson kotlin - Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
问题描述
我从Fitbit API获取json字符串.我想将dateTime和value字段保存在List对象中.我正在使用杰克逊模块科特林.我为此创建了ActivitiesSteps数据类.
I am getting a json string from Fitbit API. I want to save dateTime and value fields in a List object. I´m using jackson module kotlin. I have created ActivitiesSteps data class for this.
我不知道如何避免活动步骤"字段,我陷入困境.
I don´t know how to avoid "activities-steps" field and I´m getting stucked.
这是JSON主体(在下面的代码中的readValue方法的变量'jsonSteps'中提供):
This is the JSON body(provided in variable 'jsonSteps' to readValue method in my code below):
{
"activities-steps":[
{
"dateTime":"2018-04-17",
"value":"11045"
},
{
"dateTime":"2018-04-18",
"value":"14324"
},
{
"dateTime":"2018-05-16",
"value":"11596"
}
]
}
这是我的课程,用于保存我的数据:
Here is my class to save my data:
data class ActivitiesSteps(var dateTime: String, var value: String)
这是我使用杰克逊的代码:
Here is my code using jackson:
val mapper = jacksonObjectMapper()
val stepsList = mapper.readValue<List<ActivitiesSteps>>(jsonSteps)
并引发以下异常:
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot deserialize instance of `java.util.ArrayList` out of
START_OBJECT token at
[Source: (String)"{"activities-steps":[
{"dateTime":"2018-04-17","value":"11045"},
{"dateTime":"2018-04-25","value":"8585"},
{"dateTime":"2018-04-26","value":"11218"},
{"dateTime":"2018-04-27","value":"10462"},
{"dateTime":"2018-04"[truncated 762 chars]; line: 1, column: 1]
推荐答案
您需要具有一个与JSON顶级匹配的外部对象.在这种情况下,请将您的代码更改为:
You need to have an outer object that matches the top level of the JSON. In this case change your code to:
data class ActivityConfig(
@JsonProperty("activities-steps") val steps: List<ActivitiesSteps> = emptyList()
)
data class ActivitiesSteps(var dateTime: String, var value: String)
val stepsList = mapper.readValue<ActivityConfig>(jsonSteps).steps
如果希望列表始终存在,则可以将默认值与Jackson Kotin模块一起使用,并且如果需要,您也不需要数据类中的var
成员,val
也可以与Jackson一起正常工作除非您真的想要更改这些值.
You can use default values with the Jackson Kotin module if you want the list to always be present, and also you do not need var
members in the data class if you want, val
work fine with Jackson as well unless you really want to mutate the values.
这篇关于jackson kotlin-无法从START_OBJECT令牌中反序列化`java.util.ArrayList`的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!