将Json字符串解析为Kotlin对象与Jackson一起引发InvalidDefinitionException

时间:2018-08-19 08:46:50

标签: json spring spring-boot kotlin

我从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解析为Movie对象的我的作品:

...
    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中有些内容。

2 个答案:

答案 0 :(得分:1)

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

  

增加了对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())

答案 1 :(得分:0)

只需将@JsonIgnore注释添加到您的var id: Long?属性中