gpt4 book ai didi

java - 如何使用Gson序列化LocalDate?

转载 作者:行者123 更新时间:2023-12-02 08:40:01 26 4
gpt4 key购买 nike

我有以下POJO:

public class Round {

private ObjectId _id;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
@Getter
@Setter
@Accessors(fluent = true)
@JsonProperty("date")
private LocalDate date;

// rest of fields

}

将 POJO 转换为 JSON 的序列化方法:

public static String toJson(Object object){
return new Gson().toJson(object);
}

但是,当我调用 toJson 方法时,如下所示:

     Round round = new Round()
.userId("user3")
.course("course 1")
.date(LocalDate.now())
.notes("none");
}

return MockMvcRequestBuilders
.post("/rounds")
.accept(MediaType.APPLICATION_JSON)
.content(TestHelper.toJson(round))
.contentType(MediaType.APPLICATION_JSON);

我收到错误:com.fasterxml.jackson.databind.exc.MismatchedInputException,它引用了 POJO 的日期字段:

2020-04-25 21:19:22.269  WARN 6360 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 47] (through reference chain: com.ryd.golfstats.golfstats.model.Round["date"])]

如何使用 Gson 正确序列化 LocalDate 字段?

最佳答案

您的 POJO 使用 Jackson JSON 库中的注释,因此您应该使用其设施来序列化 LocalDate,然后一切都会正常工作:

Round r = new Round();
r.set_id(1);
r.setDate(LocalDate.now());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String rjson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(r);
System.out.println(rjson);

产生:

{
"_id" : 1,
"date" : "26-04-2020"
}

如果您因为某些原因需要使用Gson,可以查看this answer ,为LocalDate提供适配器并注册到Gson:

class LocalDateAdapter implements JsonSerializer<LocalDate> {

public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-mm-dd"
}
}
// -------
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();

关于java - 如何使用Gson序列化LocalDate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61432170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com