我创建了以下 Kotlin 数据类:
@JsonInclude(JsonInclude.Include.NON_NULL)
public data class ITunesArtist(val artistName: String,
val artistId: Long, val artistLinkUrl: URL)
(数据类是在编译时自动生成 equals、hashcode、toString 等的 Kotlin 类 - 节省时间)。
现在我尝试使用 Spring RestTemplate
填充它:
@Test
fun loadArtist()
{
val restTemplate = RestTemplate()
val artist = restTemplate.getForObject(
"https://itunes.apple.com/search?term=howlin+wolf&entity=allArtist&limit=1", ITunesQueryResults::class.java);
println("Got artist: $artist")
}
它失败了:
Could not extract response: no suitable HttpMessageConverter found for response type
[class vampr.api.service.authorization.facebook.ITunesArtist]
and content type [text/javascript;charset=utf-8]
很公平 - JSON 对象映射器可能需要 text/json
的 mime 类型。除了告诉 RestTemplate
映射到 String::class.java
,然后手动实例化 JacksonObjectMapper
的实例之外,有没有办法告诉我的 RestTemplate
将返回的 mime 类型视为 JSON?
最佳答案
除了为数据类中的所有属性提供默认值之外,您还可以使用以下命令:https://github.com/FasterXML/jackson-module-kotlin
这个 Jackson 模块将允许您序列化和反序列化 Kotlin 的数据类,而不必担心提供空的构造函数。
在 Spring Boot 应用程序中,您可以使用 @Configuration
类注册模块,如下所示:
@Configuration
class KotlinModuleConfiguration {
@Bean
fun kotlinModule(): KotlinModule {
return KotlinModule()
}
}
除此之外,您还可以使用文档中提到的扩展函数向 Jackson 注册模块。
除了支持数据类之外,您还将获得对 Kotlin stdlib 中多个类的支持,例如 Pair。
关于java - Spring Boot 将文本/javascript 序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34311181/