我从 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 的东西。
我认为您需要确保您注册了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())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句