Spring Boot将文本/ JavaScript序列化为JSON
我创建了以下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对象映射器可能期待mimetypes的text/json
。 除了告诉RestTemplate
映射到String::class.java
,然后手动实例化一个JacksonObjectMapper
实例,有没有办法告诉我的RestTemplate
将返回的MIMEtypes视为JSON?
不要为数据类中的所有属性提供默认值,你也可以使用: https : //github.com/FasterXML/jackson-module-kotlin
这个Jackson模块将允许您序列化和反序列化Kotlin的数据类,而不必担心提供一个空的构造函数。
在Spring Boot应用程序中,您可以使用@Configuration
类来注册模块,如下所示:
@Configuration class KotlinModuleConfiguration { @Bean fun kotlinModule(): KotlinModule { return KotlinModule() } }
除此之外,您还可以使用文档中提到的扩展function向Jackson注册模块。
除了支持数据类之外,您还将从Kotlin stdlib中获得对几个类的支持,例如Pair。
不确定Spring,但是Jackson需要我指定我使用了Java Bean。 您会看到,Kotlin data class
与字节代码级别上的标准Bean完全相同。
不要忘记,Java Bean规范意味着一个空的构造函数(不带参数)。 让它自动生成的一个好方法是为主构造函数的所有参数提供默认值。
序列化一个对象从jackson到字符串:
- Java Bean规范的“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模块不需要提供默认的构造函数。