Spring Boot将文本/javascript序列化为JSON
我创建了以下Kotlin数据类:Spring Boot将文本/javascript序列化为JSON,java,spring,spring-boot,kotlin,spring-rest,Java,Spring,Spring Boot,Kotlin,Spring Rest,我创建了以下Kotlin数据类: @JsonInclude(JsonInclude.Include.NON_NULL) public data class ITunesArtist(val artistName: String, val artistId: Long, val artistLinkUrl: URL) (数据类是一个Kotlin类,它在编译时自动生成equals、hashcode、toString等,从而节省时间) 现在,我尝试使用SpringRestTemplate填
@JsonInclude(JsonInclude.Include.NON_NULL)
public data class ITunesArtist(val artistName: String,
val artistId: Long, val artistLinkUrl: URL)
(数据类是一个Kotlin类,它在编译时自动生成equals、hashcode、toString等,从而节省时间)
现在,我尝试使用SpringRestTemplate
填充它:
@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类型为
text/JSON
。除了告诉restemplate
映射到String::class.java
,然后手动实例化JacksonObjectMapper
的一个实例之外,有没有办法告诉我的restemplate
将返回的mime类型作为JSON处理?对Spring不太确定,但是Jackson需要我指定我使用JavaBean。你看,Kotlin数据类
与字节码级别的标准Bean完全相同
不要忘记JavaBean规范意味着一个空构造函数(没有参数)。自动生成它的一个好方法是为主构造函数的所有参数提供默认值
要将对象从Jackson序列化为字符串,请执行以下操作:
- JavaBeans规范的“get”部分是必需的李>
- 规范的“设置”部分是必需的李>
- 此外,该对象需要一个空构造函数李>
@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模块,无需提供默认构造函数 除了为数据类中的所有属性提供默认值之外,您还可以使用: 此Jackson模块将允许您序列化和反序列化Kotlin的数据类,而无需担心提供空构造函数 在Spring引导应用程序中,您可以使用
@Configuration
类注册模块,如下所示:
@Configuration
class KotlinModuleConfiguration {
@Bean
fun kotlinModule(): KotlinModule {
return KotlinModule()
}
}
除此之外,您还可以使用文档中提到的扩展函数向Jackson注册模块
除了支持数据类之外,您还可以从Kotlin stdlib获得对几个类的支持,例如Pair。是的,差不多就是这样。实际上,我不确定字段是否必须为空。必须有默认值才能允许kotlinc生成空构造函数。嗯,我没有测试,但我99.999%确定你是对的。从记忆到理性。