我正在尝试在Gson输出中使用自定义日期格式,但.setDateFormat(DateFormat.FULL)似乎不起作用,它也一样.registerTypeAdapter(Date.class, new DateSerializer()).
这就像Gson不关心对象"Date"并以其方式打印它.
我怎么能改变呢?
谢谢
编辑:
@Entity
public class AdviceSheet {
public Date lastModif;
[...]
}
public void method {
Gson gson = new GsonBuilder().setDateFormat(DateFormat.LONG).create();
System.out.println(gson.toJson(adviceSheet);
}
Run Code Online (Sandbox Code Playgroud)
我一直用java.util.Date; setDateFormat()不起作用:(
语境
我有控制器测试。我试图使用 Gson 将对象 UserDto 转换为 Json。
问题
Gson 无法转换 LocalDate 类型的字段生日。它向我显示错误消息:无法读取 HTTP 消息:org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:意外的令牌(START_OBJECT),预期的 VALUE_STRING:预期的数组或字符串。;嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string。在 [来源: (PushbackInputStream); 行:1,列: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 …Run Code Online (Sandbox Code Playgroud)