Skip to content

Instantly share code, notes, and snippets.

@abhi2495
Last active July 19, 2020 20:33
Show Gist options
  • Save abhi2495/3af9c643cbe34a9bb0b2b0464226cc1e to your computer and use it in GitHub Desktop.
Save abhi2495/3af9c643cbe34a9bb0b2b0464226cc1e to your computer and use it in GitHub Desktop.
/*
##################################################################################
##################################################################################
######### IF YOU FOUND THIS GIST USEFUL, PLEASE LEAVE A STAR. THANKS. ############
##################################################################################
##################################################################################
*/
public final class JsonUtil {
public static ObjectMapper getMapper() {
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, new JsonSerializer<>() {
@Override
public void serialize(LocalDateTime utcDateTime, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
String dateTimeWithZone = utcDateTime.atZone(ZoneOffset.UTC).toString();
jsonGenerator.writeString(dateTimeWithZone);
}
});
ObjectMapper o = new ObjectMapper();
o.registerModules(module);
return o;
}
}

Use Case:

  • We are manually serializing the object
  • We want to serialize a particular type of field (eg. LocalDateTime type) in a custom way

How am I doing it

  • Modifying the ObjectMapper instance to create modules defining serializers for particular type and registering those modules in the ObjectMapper.
@JsonSerialize(using = EventSerializer.class)
public class Event {
private String name;
private LocalDateTime startDate;
private LocalDateTime endDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDateTime getStartDate() {
return startDate;
}
public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}
public LocalDateTime getEndDate() {
return endDate;
}
public void setEndDate(LocalDateTime endDate) {
this.endDate = endDate;
}
}
Event event = new Event();
event.setName("someEvent");
event.setStartDate(LocalDateTime.now());
event.setEndDate(LocalDateTime.now().plusDays(1));
System.out.println(JsonUtil.getMapper().writeValueAsString(event));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment