[英]jackson json date format convert
請幫助更改日期格式。
**來源** json 文件
**對象** 員工 Object
我需要支持將文件 json 日期轉換為 Object. 從文件
{
"dateOfBirth": {
"year": 1980,
"month": "MAY",
"monthValue": 5,
"dayOfMonth": 4,
"dayOfYear": 124,
"dayOfWeek": "WEDNESDAY",
"chronology": {
"calendarType": "iso8601",
"id": "ISO"
},
"era": "CE",
"leapYear": false
}
}
至 Object
{"dateOfBirth": "1980-05-04"}
Object
public class Employee {
private LocalDate dateOfBirth;
//setter
//getter
}
庫"com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
日期: java.time.LocalDate
我的目標是從文件中讀取 json 數據和 map 到 object。
您可以使用自定義反序列化器。
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.