java12399900
java12399900

Reputation: 1671

How to Serialize LocalDate using Gson?

I have the following POJO:

public class Round {

    private ObjectId _id;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    @Getter
    @Setter
    @Accessors(fluent = true)
    @JsonProperty("date")
    private LocalDate date;

    // rest of fields

}

Serializing method to convert POJO to JSON:

public static String toJson(Object object){
    return new Gson().toJson(object);
}

However when I invoke the toJson method as below:

     Round round = new Round()
            .userId("user3")
            .course("course 1")
            .date(LocalDate.now())
            .notes("none");
    }

     return MockMvcRequestBuilders
                .post("/rounds")
                .accept(MediaType.APPLICATION_JSON)
                .content(TestHelper.toJson(round))
                .contentType(MediaType.APPLICATION_JSON);

I get the error: com.fasterxml.jackson.databind.exc.MismatchedInputException that refers to the date field of the POJO:

2020-04-25 21:19:22.269  WARN 6360 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
     at [Source: (PushbackInputStream); line: 1, column: 47] (through reference chain: com.ryd.golfstats.golfstats.model.Round["date"])]

How can I correctly serialize the LocalDate field using Gson?

Upvotes: 0

Views: 7309

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

Your POJO uses annotations from Jackson JSON library, so you should have used its facilities to serialize LocalDate and everything would work fine then:

Round r = new Round();
r.set_id(1);
r.setDate(LocalDate.now());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String rjson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(r);
System.out.println(rjson);

produces:

{
  "_id" : 1,
  "date" : "26-04-2020"
}

If you need to use Gson due to some reason, you may review this answer, provide adapter for LocalDate and register it with Gson:

class LocalDateAdapter implements JsonSerializer<LocalDate> {

    public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-mm-dd"
    }
}
// -------
Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
        .create();

Upvotes: 4

Related Questions