【发布时间】:2018-09-28 14:12:23
【问题描述】:
上下文
我有控制器测试。我尝试使用 Gson 将对象 UserDto 转换为 Json。
问题
Gson 无法转换类型为 LocalDate 的字段生日。它向我显示错误消息:未能读取 HTTP 消息:org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:意外令牌(START_OBJECT),预期 VALUE_STRING:预期数组或字符串。嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException:意外令牌 (START_OBJECT),预期 VALUE_STRING:预期数组或字符串。 在 [来源:(PushbackInputStream); line: 1, column: 76](通过引用链:com.user.management.domain.User["birthday"])
@Test
public void createUser() throws Exception {
//Given
GroupOfUser groupOfUser = new GroupOfUser();
groupOfUser.setId(1L);
groupOfUser.setName("test_name");
User user = new User();
user.setId(1L);
user.setFirstName("test_firstName");
user.setLastName("test_lastName");
user.setBirthday(LocalDate.of(2011,1,1));
user.getGroupOfUsers().add(groupOfUser);
Gson gson = new Gson();
String jsonContent = gson.toJson(user);
when(userService.saveUser(any(User.class))).thenReturn(user);
//When && Then
mockMvc.perform(post("/v1/users")
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(jsonContent))
/*.andExpect(jsonPath("$.id",is(1)))*/
.andExpect(jsonPath("$.firstName", is("test_firstName")))
.andExpect(jsonPath("$.lastName", is("test_lastName")))
.andExpect(jsonPath("$.date", is(2018 - 1 - 1)));
}
提前感谢您的帮助
【问题讨论】:
-
将日期转换为时间戳并将其存储在 JSON 中是此类场景的最佳选择。也是Java中的代码吗?可能是java开发者可以确认一下,加个tag就和我不知道是不是一样。