在前端使用 fetch
进行请求时后端的 LocalDateTime
序列化正常
前端请求代码
fetch(`${ctx}/direct/game/getCurrentGame`)
.then(res => res.json())
.then(json => console.log(json));
// 返回数据
{
"code": 200,
"message": null,
"data": {
"id": 1032486183939768321,
"startTime": "2018-08-23T13:04:23",
"endTime": "2018-08-23T13:40:54",
}
}
后端 Java
测试代码
final ResultActions resultActions = restMockMvc.perform(get("/direct/game/getCurrentGame"));
final Game currentGame = action2Entity(resultActions, new TypeReference<JsonResult<Game>>() {
});
log.info("currentGame: {}", currentGame);
// action2Entity 方法大致上是这个样子
protected <T extends Serializable> T action2Entity(ResultActions resultActions, TypeReference<JsonResult<T>> type) throws IOException {
final JsonResult<T> jsonResult = om.readValue(resultActions.andReturn().getResponse().getContentAsString(), type);
return jsonResult.getData();
}
但会抛出异常
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.time.LocalDateTime out of START_ARRAY token
at [Source: {"code":200,"message":null,"data":{"id":1032486183939768321,"startTime":[2018,8,23,13,4,23],"endTime":[2018,8,23,13,40,54]}}; line: 1, column: 103] (through reference chain: com.rx.f3d.common.web.JsonResult["data"]->com.rx.f3d.module.entity.game.Game["startTime"])
所以为什么使用 SpringTest 测试与前端不一致?而且又应该怎样才能正确的序列化/反序列化 LocalDateTime
呢?
暂不考虑为什么不一致。
作为直接序列化的类,可以选择方便的序列化的类例如String,或者用@JsonSerialize,@JsonDeserialize自己写序列化/反序列化。对于时间类型序列化的话一般会有一些@DateFormat之类的现成的注解。