Jacksonjson日期格式转换器

hujrc8aj  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(128)

请帮助更改日期格式。

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"
日期:一月一日
我的目标是从文件中读取json数据并将其Map到对象。

kpbwa7wx

kpbwa7wx1#

可以使用自定义反序列化程序。

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());
  }
}

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

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

相关问题