Related code for springboot jackson settings.
@Configuration
class JacksonConfig {
@Bean
fun jackson2ObjectMapperBuilderCustomizer(): Jackson2ObjectMapperBuilderCustomizer =
Jackson2ObjectMapperBuilderCustomizer { builder ->
builder.serializerByType(Long::class.java, ToStringSerializer.instance)
}
}
But this custom serializer only works partially.
@RestController
class Controller {
@GetMapping("/1")
fun hello(): Person{
return Person(116391232976064512L)
}
@GetMapping("/2")
fun hello2(): Student{
return Student(116391232976064512L)
}
@GetMapping("/3")
fun hello3(): Product{
return Product(116391232976064512L)
}
}
data class Person(
val id: Long
)
data class Student(
val id: Long? = null
)
I created java object again to test.
public class Product {
private Long id;
public Product(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
only the /1
api successfully converts Long
to String
type, and the other two api
do not.
Am I setting the global serializer wrong?
output:
// get http://localhost:8080/1
{"id":"116391232976064512"}
// get http://localhost:8080/2
{"id":116391232976064512}
// get http://localhost:8080/3
{"id":116391232976064512}
If you look closely, you will see that only api/1
returns String
type as expected.
I am using springboot
built-in jackson support:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
result
With the help of @M.Deinum I found the problem, there was something wrong with the way kotlin was set up. reference
The correct settings are as follows:
@Configuration
class JacksonConfig {
@Bean
fun jackson2ObjectMapperBuilderCustomizer(): Jackson2ObjectMapperBuilderCustomizer =
Jackson2ObjectMapperBuilderCustomizer { builder ->
builder.serializerByType(Long::class.java, ToStringSerializer.instance)
builder.serializerByType(Long::class.javaObjectType, ToStringSerializer.instance)
}
}