请帮忙更改日期格式。
**源** 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());
}
}
然后使用@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
.