java - 当我自定义 addCorsMappings() 时,在 Json 中转换 java-object (dto) 期间,转换日期会中断

标签 java json spring-boot spring-mvc

我们需要自定义全局配置来描述请求的 cors-header 设置。

我使用SpringBoot,项目是spring boot打包在文件扩展名*.war中。

@SpringBootConfiguration
@EnableScheduling
@SpringBootApplication
public class App
        extends SpringBootServletInitializer
        implements WebApplicationInitializer {

    private static final Logger LOGGER  = LoggerFactory.getLogger( App.class );

    public static void main(String[] args) {

        LOGGER.info("Start an application...");

        SpringApplication.run(App.class, args);
    }


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

        LOGGER.info("There is building the web application!");

        return builder.sources(App.class);
    }
}

这是cors-header的设置。 我必须导入 Spring MVC 配置 (@EnableWebMvc),以便我设置的配置起作用。

@EnableWebMvc
@Configuration
public class CorsGlobalConfiguration {

 private final static String ROOT_API = "/**";

    @Bean
    public WebMvcConfigurer corsConfig(){

        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping(ROOT_API)
                        .allowedHeaders("*")
                        .allowedOrigins("*")
                .allowedMethods("GET","POST","PUT");
            }
        };
    }
}

但是客户端已经获得了数组中的 json 日期。

例如:

客户必须获得:

“2020-03-14T11:32:33”,

但是客户正在得到

[2020, 03, 14, 11, 32, 33]

Update_1

我做到了。

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper configureObjectMapper() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return objectMapper;
    }
}

这不起作用。

enter image description here

Update_2

我做到了。

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

这不起作用。

Update_3

  <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.10.3</version>
        </dependency>

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

它也不起作用。

enter image description here

Update_4

我执行了以下操作;

  • 应用程序属性
#spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
@Component
public class JacksonLocalDateSerializer extends StdSerializer<LocalDateTime> {

    private static final long serialVersionUID = -7880057299936771237L;

    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ")
                    .withResolverStyle(ResolverStyle.STRICT);

    public JacksonLocalDateSerializer(Class<LocalDateTime> t) {
        super(t);
    }

    public JacksonLocalDateSerializer() {
        this(null);
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(formatter.format(value));
    }
}
@Configuration
public class JacksonConfig {


    private JacksonLocalDateSerializer jacksonLocalDateSerializer;

    @Autowired
    public JacksonConfig(JacksonLocalDateSerializer jacksonLocalDateSerializer) {
        this.jacksonLocalDateSerializer = jacksonLocalDateSerializer;
    }

    @Bean
    @Primary
    public ObjectMapper configureObjectMapper() {

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, this.jacksonLocalDateSerializer);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        return objectMapper;
    }
}

  • dto
...
  private LocalDateTime statusDate;
...

我得到:

enter image description here

为什么会这样?

如何正确?

谁有什么想法?

Update_5

我拒绝使用@EnableWebMvc注释。

我的配置类现在是:

@Configuration
public class CorsGlobalConfiguration {

    @Value("${api.prefix}")
    private String apiPrefix;

    @Value("${header.cors.origins.allow}")
    private String [] headerCorsOriginsAllow;

    @Value("${header.cors.methods.allow}")
    private String [] headerCorsMethodsAllow;

    @Bean
    public WebMvcConfigurer corsConfig() {

        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping(apiPrefix)
                        .allowedOrigins(headerCorsOriginsAllow)
                        .allowedMethods(headerCorsMethodsAllow);
            }
        };
    }
}

问题已解决。

最佳答案

jackson-datatype-jsr310 添加到您的依赖项。

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId></artifactId>
    <version>2.9.7</version>
</dependency>

然后将以下属性添加到您的 application.properties 文件中:

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

关于java - 当我自定义 addCorsMappings() 时,在 Json 中转换 java-object (dto) 期间,转换日期会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61243834/

相关文章:

java - E4 - 如何从 SourceViewer 中删除插入符号?

java - WildFly + java首选项在类路径中找不到自定义首选项类

java - 如何在 java 中将 json 作为 Rest Post Web 服务的查询参数传递

Python,使用 json.dumps() 导入的字符串无法被 if 语句识别,为什么不呢?

spring-boot - 使用 Spring Cloud Config 进行属性版本控制

docker - 如何使用 Docker 配置带有 redis 的 spring boot web 应用程序

java - 多模块JHipster应用程序

java - 如何将附加数据传递给 Mapper?

java - Spock + Spring Boot Web - 获取异常消息

php - 使用 JSON 的 MySQL 查询