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

标签 java json api jackson

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

大多数看起来像:

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

但其中一些是这样的:

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

我想要解析的 java 对象字段

private Date publishedDate;

我收到此错误:

 Cannot deserialize value of type `java.util.Date` from String "2001-01": not a valid representation (error: Failed to parse Date value '2001-01': Cannot parse date "2001-01": while it seems to fit format 'yyyy-MM-dd', parsing fails (leniency? null))

最佳答案

您需要为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}]

关于java - 如何反序列化不同格式的日期: YYYY-MM-DD and YYYY-MM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099794/

相关文章:

java - 转换 CRUD JSP 应用程序以在 CQ5 (OSGi) 中使用

java - 将 EditText 可见性更改为隐藏

java - 如何在 session 超时时调用 sessionDestroyed

PHP 将 JSON 字符串回显到 HTML 输入值中 - 需要字符转义

c# - JSON 补丁更新嵌套对象

javascript - 使用单引号内的转义引号解析 JSON 时出错

java - 使用 Swagger-UI @ApiParam 注释 @FormParam 字段

java - 如何从 Java HttpClient 获取重定向 url

Python Rest客户端api上传文件

mongodb - 将 RShiny 应用程序重新编码为 React 应用程序 - 如何将我的数据获取到我的 React 应用程序