我有一个日期如下的json文件:

{
...
  "dob":"20001010",
  "registerdate":"20001010121212",
...
}


我在课堂上使用:

public class User implements Serializable {
... some other
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd
    public java.util.Date dob; // this works

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMddHHmmss")
    public java.util.Date registerdate;
}



然后在我的测试中,我使用Gson来转换文件

User user = new Gson().fromJson("user.json", User.class);


但是当运行时,我得到:

com.google.gson.JsonSyntaxException: 20001010121212


我与:yyyyMMddHHmmss或YYYYMMddHHmmss或YYYYMMDDHHmmss相同

pom:

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

最佳答案

基本上com.google.gson.Gson无法识别注释com.fasterxml.jackson.annotation.JsonFormat(两个不同的库)

这是仅使用fasterxml lib中的ObjectMapper的另一种解决方案

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.Serializable;
import java.util.Date;

public class DemoApplication {
    public static void main(String[] args) throws JsonProcessingException {
        String json = "{\"dob\":\"20001010121212\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(json, User.class);
        System.out.println(user.dob);
    }
}

class User implements Serializable {
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMddHHmmss")
    public Date dob;
}

10-06 09:41