Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot serialize text/javascript to JSON

I created the following Kotlin data class:

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

(a data class is a Kotlin class that auto-generates equals, hashcode, toString etc at compile time - saves time).

Now I've tried populating it using 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")
}

It fails with:

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]

Fair enough - the JSON object mapper was probably expecting mime-type of text/json. Other than telling RestTemplate to map to String::class.java, and then instantiating an instance of JacksonObjectMapper by hand, is there a way to tell my RestTemplate to treat the returned mime type as JSON?

like image 352
Jasper Blues Avatar asked Jun 19 '26 10:06

Jasper Blues


1 Answers

Instead of providing defaults for all properties in your data class you can also use this: https://github.com/FasterXML/jackson-module-kotlin

This Jackson module will allow you to serialize and deserialize Kotlin's data classes without having to worry about providing an empty constructor.

In a Spring Boot Application you can register the module with a @Configuration class like so:

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

Other than that you can also use the extension functions mentioned in the documentation to register the module with Jackson.

Besides supporting data classes you will also get support for several classes from the Kotlin stdlib, like Pair for example.

like image 56
mhlz Avatar answered Jun 21 '26 00:06

mhlz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!