将日期时间格式从Web服务转换为字符串

时间:2016-06-08 06:20:50

标签: spring mongodb rest datetime

这是我的POM.xml ..错误是覆盖joda-time的托管版本2.8.2

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>gs-rest-service-cors</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>


<dependencies>

<dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
        <version>2.4.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>


    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>


</dependencies>


<properties>
    <java.version>1.8</java.version>
</properties>


<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

我在网络服务上的json数据

 [{"id":2,"cameraid":"004","timestamp":{"centuryOfEra":20,"yearOfEra":2016,"yearOfCentury":16,"weekyear":2016,"monthOfYear":11,"weekOfWeekyear":48,"dayOfMonth":29,"dayOfWeek":2,"era":1,"dayOfYear":334,"year":2016,"millisOfSecond":0,"millisOfDay":5521000,"secondOfMinute":1,"secondOfDay":5521,"minuteOfHour":32,"minuteOfDay":92,"hourOfDay":1,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"},"millis":1480354321000,"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"}},"afterNow":true,"beforeNow":false,"equalNow":false},"filename":"ogh.png"}
,{"id":3,"cameraid":"002","timestamp":{"centuryOfEra":20,"yearOfEra":2015,"yearOfCentury":15,"weekyear":2015,"monthOfYear":6,"weekOfWeekyear":25,"dayOfMonth":15,"dayOfWeek":1,"era":1,"dayOfYear":166,"year":2015,"millisOfSecond":982,"millisOfDay":81921982,"secondOfMinute":21,"secondOfDay":81921,"minuteOfHour":45,"minuteOfDay":1365,"hourOfDay":22,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"},"millis":1434379521982,"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"}},"afterNow":false,"beforeNow":true,"equalNow":false},"filename":"ydd.png"},

我的模特课:

public class Record {

@Id private Long id;
private String cameraid;
private DateTime timestamp;
private String filename;


public Record(Long id,String cameraid, DateTime timestamp, String filename) {
    this.id = id;
    this.cameraid = cameraid;
    this.timestamp = timestamp;
    this.filename = filename;
}

我的控制器类:

@Autowired
RecordRepository rep;

@RequestMapping(value="list")
public List<Record> getList() {
List<Record> recordList = rep.findAll(); 
return recordList;

MongoRepository类:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface RecordRepository extends MongoRepository<Record, String> {

}

如何在网络服务上以此格式显示时间戳(2016-07-16T19:20:30 + 01:00)?

1 个答案:

答案 0 :(得分:2)

有两种方法可以实现这一目标。

  1. 使用Jackson Serializers - 进行全球转换。适用于每次转化
  2. 用户Spring WebDataBinder和PropertyEditorSupport。您可以选择需要此转换的控制器
  3. 实施杰克逊序列化

    将上述课程注册到杰克逊模块

    public class CustomDateTimeSerializer extends JsonSerializer<DateTime> {
        // Customize format as per your need 
        private static DateTimeFormatter formatter = DateTimeFormat
                .forPattern("yyyy-MM-dd'T'HH:mm:ss");
    
        @Override
        public void serialize(DateTime value, JsonGenerator generator,
                              SerializerProvider serializerProvider)
                throws IOException {
            generator.writeString(formatter.print(value));
        }
    
    }
    

    将序列化程序添加到Jackson模块

    @Configuration
    public class JacksonConfiguration {
    
        @Bean
        public JodaModule jacksonJodaModule() {
            final JodaModule module = new JodaModule();
            module.addSerializer(DateTime.class, new CustomDateTimeSerializer());
            return module;
        }
    }
    

    使用WebBinder API和PropertyEditorSupport

    实施PropertyEditorSupport

    public class DateTimeEditor extends PropertyEditorSupport {
    
        private final DateTimeFormatter formatter;
    
        public DateTimeEditor(String dateFormat) {
            this.formatter = DateTimeFormat.forPattern(dateFormat);
        }
    
        public String getAsText() {
            DateTime value = (DateTime) getValue();
            return value != null ? value.toString(formatter) : "";
        }
    
        public void setAsText( String text ) throws IllegalArgumentException {
            if ( !StringUtils.hasText(text) ) {
                // Treat empty String as null value.
                setValue(null);
            } else {
                setValue(new DateTime(formatter.parseDateTime(text)));
            }
        }
    }
    

    将此PropertyEditor添加到Rest Controller

    @RestController
    @RequestMapping("/abc")
    public class AbcController {
    
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.registerCustomEditor(DateTime.class, new DateTimeEditor("yyyy-MM-dd", false));
        }
    
    }