将 JSON 反序列化为<SomeType> Kotlin + Jackson 的列表 - 反序列化异常



我按照以下链接使用映射器从 json 字符串读取值,但我在执行代码时可以看到一种反序列化异常,

如何使用杰克逊反序列化为 Kotlin 集合

法典:

private fun parseCountry(): List<Country> {
val map = jacksonObjectMapper()
val countryAsString = """[
{
"countryCode": "IND",
"countryName": "INDIA"
}
]"""
return map.readValue(countryAsString)
}

国家.kt

data class Country(
val countryCode: String,
val countryName: String)

例外:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is feign.codec.DecodeException: Error while extracting response for type [java.util.List<com.test.Country>] and content type [application/json;charset=UTF-8]; nested exception is 
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList<com.test.Country>` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<com.test.Country>` out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 1]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at com.financing.platform.mdc.filters.UserMdcFilter.doFilter(UserMdcFilter.java:23)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)

我试图挖掘这么多并找到根本原因,但无法找到,因此请与这里的专家联系以获取可能的解决方案。

PS:我正在使用的版本是

<kotlin.version>1.3.70</kotlin.version>
<jackson.version>2.9.10</jackson.version>

Jackson 对 kotlin 数据类有问题。因为它需要在属性中具有默认的无参数构造函数和 setter。

为了解决这个问题,您可以将 kotlin 模块注册到 jackson 映射器,这样您就可以用我们的问题反序列化数据类。

首先,您必须添加依赖项

<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.11.0</version>
</dependency>

然后在jacksonObjectMapper中注册模块

val mapper = ObjectMapper().registerModule(KotlinModule())

完成此操作后,它应该不会失败

https://github.com/FasterXML/jackson-module-kotlin

最新更新