账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    SpringBoot 使用 Java8 时间 API 序列化异常
    30
    0

    在前端使用 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 呢?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 乄風飛シ 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部