【问题标题】:Spring Boot serialize text/javascript to JSONSpring Boot 将文本/javascript 序列化为 JSON
【发布时间】:2016-03-22 12:57:11
【问题描述】:

我创建了以下 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 类型为 text/json。除了告诉RestTemplate 映射到String::class.java,然后手动实例化JacksonObjectMapper 的实例之外,有没有办法告诉我的RestTemplate 将返回的mime 类型视为JSON?

【问题讨论】:

    标签: java spring spring-boot kotlin spring-rest


    【解决方案1】:

    不确定 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 模块消除了提供默认构造函数的需要。

    【讨论】:

    • 是的,差不多就是这样。
    • 实际上我不确定字段必须可以为空。必须有默认值才能让 kotlinc 生成一个空的构造函数。
    • 嗯,我没有测试,但我有 99.999% 的把握你是对的。凭记忆,这是有道理的。
    【解决方案2】:

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

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2019-10-03
      相关资源
      最近更新 更多