0

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

silverwind
  • 21
  • 2
  • 8
  • Converting the date to timestamp and storing it in JSON is the best option for such scenarios. Also is the code in Java? May be a java developer can confirm, add a tag for the same as I am not sure if it is. – Saurabh Harwande Apr 18 '18 at 11:02
  • Possible duplicate of [Serialize Java 8 LocalDate as yyyy-mm-dd with Gson](https://stackoverflow.com/questions/39192945/serialize-java-8-localdate-as-yyyy-mm-dd-with-gson) – ghn1712 Aug 23 '18 at 21:04

2 Answers2

8

Include in your pom.xml:

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

Then in your User.java import ToStringSerializer as follows:

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

And finally, always in your User.java file, annotate the interested dates like this:

@JsonSerialize(using = ToStringSerializer.class) 
private LocalDate birthday;
Luca Tampellini
  • 1,759
  • 17
  • 23
0

Unfortunately GSON doesn't have a support for local date time, so you will need to create your custom serialize, as did here https://stackoverflow.com/a/39193077/9091513

ghn1712
  • 105
  • 1
  • 3
  • 15