在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ SpringBoot 使用 Java8 時間 API 序列化異常

SpringBoot 使用 Java8 時間 API 序列化異常

在前端使用 fetch 進行請求時后端的 LocalDateTime 序列化正常

前端請求代碼

fetch(`${ctx}/direct/game/getCurrentGame`)
        .then(res => res.json())
        .then(json => console.log(json));

// 返回數(shù)據(jù)
{
    "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 呢?

回答
編輯回答
櫻花霓

date format 指定下格式

@Column(name = "startTime")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startTime;
2017年12月5日 19:44
編輯回答
未命名

暫不考慮為什么不一致。

作為直接序列化的類,可以選擇方便的序列化的類例如String,或者用@JsonSerialize,@JsonDeserialize自己寫序列化/反序列化。對于時間類型序列化的話一般會有一些@DateFormat之類的現(xiàn)成的注解。

2018年7月3日 15:33