我想将springboot项目从1.5.1迁移到2.0.1。
但是当我在RestController中返回模型时,即时格式是不同的。
返回对象:
public class Message {
private Instant instant;
}
在1.5.1中:
{
"instant": {
"epochSecond": 1537263091,
"nano": 557000000
}
}
在2.0.1中:
{
"instant": "2018-09-18T09:46:02.646Z"
}
我如何得到这个{ “即时”:{ “ epochSecond”:1537263091, “纳米”:557000000 } }当我使用2.0.1时?
答案 0 :(得分:2)
您可能可以在application.properties上设置此操作:
spring.jackson.serialization.write_dates_as_timestamps=false
在迁移中,如果添加了以下任何依赖项,请尝试将其删除:
jackson-modules-java8
jackson-datatype-jsr310
[已更新]
另一种方法,您可以为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();
}
}
}
并拥有一个Configuration类,将Instant设置为使用您的序列化器:
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;
}
}