我有以下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"])]
如何LocalDate
使用正确序列化字段Gson
?
您的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,则可以查看以下答案,提供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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句