【问题标题】:Kotlin | Jackson annotation | How to fix Out of START_ARRAY token Error科特林 |杰克逊注解 |如何修复超出 START_ARRAY 令牌错误
【发布时间】:2021-09-17 06:54:00
【问题描述】:

谁能说我哪里做错了。我有这样的json

[
  {
    "id": "1",
    "name": "ff",
    "surname": "ggg",
    "cap": "10000"
  },
  {
    "id": "1",
    "name": "aaa",
    "surname": "hhh",
    "cap": "22222"
  },
  {
    "id": "1",
    "name": "rrr",
    "surname": "hhhhhdr",
    "cap": "33333"
  },
  {
    "id": "1",
    "name": "hhh",
    "surname": "qqqqq",
    "cap": "44444"
  }
]

我解析到这个类。

data class ResponseList(
    val capList: List<Response>?
) {
    data class Response(
        @JsonProperty("id")
        val id: String,
        @JsonProperty("name")
        val name: String,
        @JsonProperty("surname")
        val surname: String,
        @JsonProperty("cap")
        val cap: String
    )
}

当我尝试解析它时,列表始终为空,如果我尝试对其进行测试,则会出现以下错误: 无法从数组值反序列化 com.myapp.ResponseList 类型的值(令牌 JsonToken.START_ARRAY

【问题讨论】:

  • 如果你解析为ResponseList,它会期望你的JSON类似于{ capList: [{id: "", name: "", surname: "", cap: ""}] }

标签: android json kotlin parsing jackson


【解决方案1】:

只需要类响应,如下所示:

fun test(){
    val jsonStr = "your json str"
    val mapper = ObjectMapper()
    val lendReco: List<Response> =
        mapper.readValue(jsonStr, object : TypeReference<List<Response?>?>() {})
}

data class Response(
    @JsonProperty("id")
    val id: String,
    @JsonProperty("name")
    val name: String,
    @JsonProperty("surname")
    val surname: String,
    @JsonProperty("cap")
    val cap: String
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-19
    • 2018-04-03
    • 2018-08-25
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2017-02-15
    • 2016-08-09
    相关资源
    最近更新 更多