jackson json 日期格式转换

jackson json date format convert

请帮助更改日期格式。

**来源** json 文件

**目标**员工对象

我需要支持将文件 json 日期转换为对象。来自文件

{
 "dateOfBirth": {
    "year": 1980,
    "month": "MAY",
    "monthValue": 5,
    "dayOfMonth": 4,
    "dayOfYear": 124,
    "dayOfWeek": "WEDNESDAY",
    "chronology": {
      "calendarType": "iso8601",
      "id": "ISO"
    },
    "era": "CE",
    "leapYear": false
  }
}

对象

{"dateOfBirth": "1980-05-04"}

对象

public class Employee {   
    private LocalDate dateOfBirth;
    //setter
    //getter
}

图书馆 "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"

日期:java.time.LocalDate

我的目标是从文件中读取 json 数据并将其映射到对象。

您可以使用自定义解串器。

public class EmployeeBirthDateDeserializer extends StdDeserializer<LocalDate> {

  public EmployeeBirthDateDeserializer() {
    super(LocalDate.class);
  }

  @Override
  public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonNode root = parser.getCodec().readTree(parser);
    return LocalDate.of(root.get("year").asInt(), root.get("monthValue").asInt(), root.get("dayOfMonth").asInt());
  }
}

然后仅将其应用于 Employee 中的 dateOfBirth 字段,使用 @JsonDeserialize:

public class Employee {

  @JsonDeserialize(using = EmployeeBirthDateDeserializer.class)
  private LocalDate dateOfBirth;

  //getters and setter
}

测试:

public class Temp {

  public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Employee employee = mapper.readValue(ClassLoader.getSystemResourceAsStream("strange-date.json"), Employee.class);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    System.out.println(formatter.format(employee.getDateOfBirth()));
  }
}

打印:1980-05-04