3

我创建了以下 Kotlin 数据类:

@JsonInclude(JsonInclude.Include.NON_NULL)
public data class ITunesArtist(val artistName: String, 
    val artistId: Long, val artistLinkUrl: URL)

(数据类是 Kotlin 类,它在编译时自动生成 equals、hashcode、toString 等 - 节省时间)。

现在我尝试使用 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 对象映射器可能期待 mime-type 的text/json. 除了告诉RestTemplatemap to String::class.java,然后JacksonObjectMapper手动实例化一个实例之外,有没有办法告诉我RestTemplate将返回的 mime 类型视为 JSON?

4

2 回答 2

3

不确定 Spring,但 Jackson 需要我指定我使用的是 Java Bean。你看,Kotlindata class与字节码级别的标准 Bean 完全一样。

不要忘记 Java Bean 规范暗示了一个空的构造函数(没有参数)。自动生成它的一个好方法是为主构造函数的所有参数提供默认值。

要将对象从 Jackson 序列化为 String:

  • Java Beans 规范的“get”部分是必需的。

将 JSON 字符串读取到对象:

  • 规范的“设置”部分是必需的。
  • 此外,该对象需要一个空的构造函数。

修改类以包括:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data public class ITunesArtist(var artistName: String? = null, 
    var artistId: Long = -1L, val amgArtistId: String = "id", 
    var artistLinkUrl: URL? = null)
  • 字段提供默认值以便有一个空的构造函数。

编辑:

使用@mhlz(现已接受)答案中的 Kotlin 模块消除了提供默认构造函数的需要。

于 2015-12-16T23:58:25.700 回答
3

除了为数据类中的所有属性提供默认值,您还可以使用它:https ://github.com/FasterXML/jackson-module-kotlin

这个 Jackson 模块将允许您序列化和反序列化 Kotlin 的数据类,而不必担心提供空的构造函数。

在 Spring Boot 应用程序中,您可以使用@Configuration如下类注册模块:

@Configuration
class KotlinModuleConfiguration {
    @Bean
    fun kotlinModule(): KotlinModule {
        return KotlinModule()
    }
}

除此之外,您还可以使用文档中提到的扩展功能向 Jackson 注册模块。

除了支持数据类之外,您还将获得对来自 Kotlin 标准库的多个类的支持,例如 Pair。

于 2015-12-21T15:24:50.377 回答