json LocalDate
时间: 2024-01-10 09:20:55 浏览: 171
在Java中,将JSON字符串中的日期转换为LocalDate对象可以通过使用Jackson库来实现。下面是两种方法:
方法一:使用@JsonFormat注解
```java
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
String json = "{\"date\": \"2022-01-01\"}";
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(json, MyObject.class);
System.out.println(myObject.getDate()); // 输出:2022-01-01
}
static class MyObject {
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
}
}
```
方法二:自定义反序列化器
```java
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) throws Exception {
String json = "{\"date\": \"2022-01-01\"}";
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
objectMapper.registerModule(module);
MyObject myObject = objectMapper.readValue(json, MyObject.class);
System.out.println(myObject.getDate()); // 输出:2022-01-01
}
static class MyObject {
private LocalDate date;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
}
static class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String dateString = p.getText();
return LocalDate.parse(dateString);
}
}
}
```
阅读全文