Reputation: 3
I want to migrate my springboot project from 1.5.1 to 2.0.1.
But the Instant format are different when I return the model in RestController.
Return object:
public class Message {
private Instant instant;
}
In 1.5.1:
{
"instant": {
"epochSecond": 1537263091,
"nano": 557000000
}
}
In 2.0.1:
{
"instant": "2018-09-18T09:46:02.646Z"
}
How can I get this one { "instant": { "epochSecond": 1537263091, "nano": 557000000 } } when I use 2.0.1?
Upvotes: 0
Views: 163
Reputation: 2220
You could probably set this operation on your application.properties:
spring.jackson.serialization.write_dates_as_timestamps=false
On the migration, if you added any of the following dependencies, try removing it:
jackson-modules-java8
jackson-datatype-jsr310
[UPDATED]
Another way, you could write a serializer for Instant:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.Instant;
public class CustomInstantSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeObject(new EpochInstant(o));
}
public static class EpochInstant {
private final long epochSecond;
private final int nano;
EpochInstant(Instant instant) {
this.epochSecond = instant.getEpochSecond();
this.nano = instant.getNano();
}
}
}
And have a Configuration class, setting the Instant to use your serializer:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.time.Instant;
@Configuration
public class JacksonConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Instant.class, new CustomInstantSerializer());
return objectMapper;
}
}
Upvotes: 2