简体   繁体   English

将java.util.Date转换为json格式

[英]Convert java.util.Date to json format

I have to convert my POJO to JSON string in order to send to client code. 我必须将POJO转换为JSON字符串才能发送到客户端代码。

When I do this however, java.util.Date field (having value " 2107-06-05 00:00:00.0 ") from within my POJO gets translated as " 1496592000000 " which I think is a time since epoch. 但是,当我这样做时,POJO java.util.Date字段(值“ 2107-06-05 00:00:00.0 ”)被翻译为“ 1496592000000 ”,我认为这是一个纪元以来。 I want it to be something more readable in Json may be in 'DD/MM/YYYY' format. 我希望它在Json中更具可读性,可能是“ DD / MM / YYYY”格式。

I am using RestEasy controller in Spring Boot application which handles the conversion for the Java object to JSON. 我在Spring Boot应用程序中使用RestEasy控制器,该控制器处理Java对象到JSON的转换。

Any clues what is going wrong? 任何线索出了什么问题?

RestEasy supports JSON via Jackson, so you can handle Date serialization in several ways. RestEasy通过Jackson支持JSON,因此您可以通过多种方式处理Date序列化。

1. @JsonFormat annotation 1. @JsonFormat批注

If you want to format specific field - simply add @JsonFormat annotation to your POJO. 如果要格式化特定字段,只需将@JsonFormat批注添加到POJO。

public class TestPojo {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    public Date testDate;
}

2. Jackson properties 2.杰克逊属性

If you want to set Date serialization format globally - you have to tune Jackson configuration properties. 如果要全局设置Date序列化格式,则必须调整Jackson配置属性。 Eg for application.properties file format. 例如, application.properties文件格式。

First one disables WRITE_DATES_AS_TIMESTAMPS serialization feature : 第一个禁用WRITE_DATES_AS_TIMESTAMPS 序列化功能

spring.jackson.serialization.write-dates-as-timestamps=false

Second one defines date format: 第二个定义日期格式:

spring.jackson.date-format=dd-MM-yyyy

Or, for application.yml file format: 或者,对于application.yml文件格式:

spring:
  jackson:
    date-format: "dd-MM-yyyy"
    serialization:
      write_dates_as_timestamps: false

3. Custom Serializer 3.自定义序列化器

If you want to take full control over serialization - you have to implement a custom StdSerializer . 如果要完全控制序列化,则必须实现自定义StdSerializer

public class CustomDateSerializer extends StdSerializer<Date> {

    private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

    public CustomDateSerializer() {
        this(null);
    }

    public CustomDateSerializer(Class t) {
        super(t);
    }

    @Override
    public void serialize(Date date, JsonGenerator generator, SerializerProvider provider) 
        throws IOException, JsonProcessingException {

        generator.writeString(formatter.format(date));
    }
}

And then use it with @JsonSerialize : 然后将其与@JsonSerialize一起使用

public class TestPojo {

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date testDate;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM