jackson kotlin - Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token

半城伤御伤魂 提交于 2019-12-11 01:07:39

问题


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.

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)

And the following exception is thrown:

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]

回答1:


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

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.




回答2:


The problem is that the array you're trying to get at is wrapped in an object, which you're feeding into Jackson and asking for a List back. JSON object-to-Java List isn't a translation that Jackson understands, so it's choking.

I would create a class that wraps that List and try deserializing to that.



来源:https://stackoverflow.com/questions/50475405/jackson-kotlin-cannot-deserialize-instance-of-java-util-arraylist-out-of-sta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!