【问题标题】:Springboot 1.5.1 migrate to 2.0.1 Instance formatSpringboot 1.5.1 迁移到 2.0.1 实例格式
【发布时间】:2018-09-18 10:02:24
【问题描述】:

我想将我的 springboot 项目从 1.5.1 迁移到 2.0.1。

但是当我在 RestController 中返回模型时 Instant 格式不同。

返回对象:

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 时?

【问题讨论】:

    标签: java spring-boot jackson gson


    【解决方案1】:

    您可能可以在您的 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();
            }
        }
    }
    

    并有一个配置类,设置 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;
        }
    }
    

    【讨论】:

    • 没有。 springboot 1.5.1 中的日期格式不是时间戳格式。如果将其设置为 false,则什么都不会改变。如果将该属性设置为 true,您会发现输出为 {"instant": 1537267373.794}。我想要的是一个 {"instant": {"epochSecond": 1537267373,"nano": 794000000}}
    • 好吧,干得好。我认为添加@Configuration 和JsonSerializer 对我来说很好。此外,我还发现了一些其他方法,例如排除 Jackson 并改用 gson。但我更喜欢你的回答。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多