科特林 |杰克逊注解 |如何修复 START_ARRAY 令牌错误

时间:2021-07-06 16:08:56

标签: android json kotlin parsing jackson

谁能说我哪里做错了。我有这样的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
    )
}

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

1 个答案:

答案 0 :(得分:0)

只需要 class Response,如下所示:

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
)