【问题标题】:How do you convert the LocalDate field to Json?如何将 LocalDate 字段转换为 Json?
【发布时间】: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就和我不知道是不是一样。

标签: json testing gson


【解决方案1】:

包含在你的 pom.xml 中:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.5</version>
</dependency>

然后在你的User.java 中导入ToStringSerializer 如下:

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 

最后,总是在你的User.java 文件中,像这样注释感兴趣的日期:

@JsonSerialize(using = ToStringSerializer.class) 
private LocalDate birthday;

【讨论】:

    【解决方案2】:

    很遗憾,GSON 没有本地日期时间的 support,因此您需要创建自定义序列化,就像这里 https://stackoverflow.com/a/39193077/9091513 所做的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 2016-02-23
      • 2011-02-12
      • 2011-08-01
      • 2019-01-11
      相关资源
      最近更新 更多