如何反序列化日期的不同格式:YYYY-MM-DD和YYYY-MM

时间:2019-05-12 13:37:59

标签: java json api jackson

我有json对象列表,其中一个字段是date。问题在于日期以不同的方式写入json。

其中大多数看起来像:

[
[
[1,6,11],
[2,7,12],
[3,8,13],
[4,9,14],
[5,10,15]
],.......
]

但是其中一些就像:

 "publishedDate": "2005-01-28"
 "publishedDate": "2011-08-29"
 "publishedDate": "2016-04-19"

我要解析的Java对象字段

"publishedDate": "1998-11"
"publishedDate": "2001-01"

我收到此错误:

private Date publishedDate;

1 个答案:

答案 0 :(得分:1)

您需要为Date编写自定义反序列化器,并且在两种情况下都必须正确转换为预期日期。在下面,您可以找到简单的示例该怎么做:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        TypeReference<List<Item>> typeReference = new TypeReference<List<Item>>() {
        };
        List<Item> readValue = mapper.readValue(jsonFile, typeReference);
        System.out.println(readValue);

    }
}

class DifferentFormatsDateJsonDeserializer extends JsonDeserializer<Date> {

    private DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private DateTimeFormatter yearMonthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");


    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String value = p.getValueAsString();
        try {
            if (value.length() == 7) {
                YearMonth yearMonth = YearMonth.parse(value, yearMonthFormatter);
                return convertToDateViaInstant(yearMonth.atDay(1));
            } else {
                LocalDate localDate = LocalDate.parse(value, localDateFormatter);
                return convertToDateViaInstant(localDate);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    public Date convertToDateViaInstant(LocalDate dateToConvert) {
        return Date.from(dateToConvert.atStartOfDay()
                .atZone(ZoneId.systemDefault())
                .toInstant());
    }
}

class Item {

    @JsonDeserialize(using = DifferentFormatsDateJsonDeserializer.class)
    private Date publishedDate;

    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }

    @Override
    public String toString() {
        return "Item{" +
                "publishedDate=" + publishedDate +
                '}';
    }
}

上述用于JSON有效载荷的程序:

[
  {
    "publishedDate": "2005-01-28"
  },
  {
    "publishedDate": "1998-11"
  }
]

打印:

[Item{publishedDate=Fri Jan 28 00:00:00 CET 2005}, Item{publishedDate=Sun Nov 01 00:00:00 CET 1998}]