mercredi 18 avril 2018

How do you convert the LocalDate field to Json?

Context

I have controller test . I trying to convert object UserDto to Json using to Gson.

Problem

Gson can't convert field birthday which is type LocalDate. It showing me error message: failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string. at [Source: (PushbackInputStream); line: 1, column: 76] (through reference chain: 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)));
}

Thank you in advance for your help

Aucun commentaire:

Enregistrer un commentaire