【发布时间】:2020-04-25 20:27:32
【问题描述】:
我有以下 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 的 date 字段:
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 字段?
【问题讨论】:
-
为什么不用Jackson的ObjectMapper来获取json字符串呢?很可能,Gson 不知道所有这些注释
-
能不能展示一下这个api的控制器方法
/rounds
标签: java json spring serialization gson