首页 > 解决方案 > 将 Json 字符串解析为 Kotlin 对象会与 Jackson 一起引发 InvalidDefinitionException

问题描述

我从 API 获得了一个 Json 字符串,并希望将其解析为 Kotlin 对象。

我的杰森:

{
  "Title": "The Secret Life of Walter Mitty",
  "Year": "2013",
  "Rated": "PG",
  "Released": "25 Dec 2013",
  "Runtime": "114 min",
  "Genre": "Adventure, Comedy, Drama",
  "Director": "Ben Stiller",
  "Writer": "Steve Conrad (screenplay by), Steve Conrad (screen story by), James Thurber (based on the short story by)",
  "Actors": "Ben Stiller, Kristen Wiig, Jon Daly, Kathryn Hahn",
  "Language": "English, Spanish, Icelandic",
  "Country": "USA, UK",
  "Awards": "5 wins & 18 nominations.",
  "Poster": "https://m.media-amazon.com/images/M/MV5BODYwNDYxNDk1Nl5BMl5BanBnXkFtZTgwOTAwMTk2MDE@._V1_SX300.jpg",
  "Ratings": [
    {
      "Source": "Internet Movie Database",
      "Value": "7.3/10"
    },
    {
      "Source": "Rotten Tomatoes",
      "Value": "51%"
    },
    {
      "Source": "Metacritic",
      "Value": "54/100"
    }
  ],
  "Metascore": "54",
  "imdbRating": "7.3",
  "imdbVotes": "265,701",
  "imdbID": "tt0359950",
  "Type": "movie",
  "DVD": "15 Apr 2014",
  "BoxOffice": "${'$'}33,223,430",
  "Production": "20th Century Fox",
  "Website": "http://WalterMitty.com",
  "Response": "True"
}

我的 Kotlin 电影对象:

@JsonIgnoreProperties(ignoreUnknown = true)
data class Movie(

    var id: Long?,

    @JsonProperty("Title")
    var title: String,

    @JsonProperty("Released")
    var release: String,

    @JsonProperty("Runtime")
    var runtime: String,

    @JsonProperty("Genre")
    var genre: String,

    @JsonProperty("Director")
    var director: String,

    @JsonProperty("Actors")
    var actor: String,

    @JsonProperty("Plot")
    var description: String,

    @JsonProperty("Poster")
    var posterLink: String?,

    @JsonProperty("Metascore")
    var metaScoreRating: String
)

我将 Json 解析为电影对象的部分:

...
    var mapper = ObjectMapper()
    mapper.readValue(jsonFromAPI, Movie::class.java)
...

但是当我运行这个片段时,我得到了这个异常:

InvalidDefinitionException: Invalid type definition for type `model.Movie`: Argument #0 of constructor [constructor for model.Movie, annotations: [null]] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator

但我不知道为什么.. Kotlin 数据类构建每个构造函数,所以我不必声明一个特定的构造函数.. 我猜 Id 有一些东西。

标签: jsonspringspring-bootkotlin

解决方案


我认为您需要确保注册jackson kotlin 模块,例如添加对数据类的支持。

添加对 Kotlin 类和数据类的序列化/反序列化支持的模块。以前,默认构造函数必须存在于 Kotlin 对象上,Jackson 才能反序列化到对象中。通过该模块,可以自动使用单个构造函数类,也支持具有二级构造函数或静态工厂的类。

有了它,您可以创建一个ObjectMapper已经使用com.fasterxml.jackson.module.kotlin.ExtensionsKt#jacksonObjectMapper. (请注意如何使用它提供的扩展之一来避免声明有效负载类)

var mapper = jacksonObjectMapper()
val movie: Movie = mapper.readValue(payload)

作为替代方案,您仍然可以创建对象映射器并使用常用 API 注册模块:

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

推荐阅读