java - Spring Boot 将文本/javascript 序列化为 JSON

标签 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)

(数据类是在编译时自动生成 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/

相关文章:

Java Spring - HttpClient 在序列化 ResponseEntity 时分配一个额外的字段

spring-boot - 以下方法不存在 : 'org.springframework.plugin.core.PluginRegistry org.springframework.plugin.core.PluginRegistry.of(java.util.List)'

java - Log4j2 不登录日志文件

java - 如何读取HTTP自定义错误字符串

java - 如果我在 Android 中使用 SSLSocket 并将密码硬编码到源代码中的信任库,那不安全吗?

java - Spring boot 请求超时

spring - "Unrecognized field (..), not marked as ignorable"当 jaxb 解码 xml 输入时

java - 在没有 API 网关的情况下处理 https 请求

java - 我的程序遇到了一些难题(注意不能使用 ArrayList)

java - Spring Boot,如何从另一个类访问 map ?