Last active
August 18, 2021 21:28
-
-
Save bcalmac/4c426f3155ef6d93fe985600ab169883 to your computer and use it in GitHub Desktop.
Jackson serialization for Interval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.Instant; | |
import org.threeten.extra.Interval; | |
import com.fasterxml.jackson.annotation.JsonAutoDetect; | |
import com.fasterxml.jackson.annotation.JsonCreator; | |
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; | |
import com.fasterxml.jackson.annotation.JsonProperty; | |
// Exclude JavaBean properties that are not part of the state | |
@JsonIgnoreProperties({ "empty", "unboundedStart", "unboundedEnd" }) | |
// Jackson does not support @JsonCreator with mix-ins | |
// https://github.com/FasterXML/jackson-databind/issues/1820 | |
// I use the private constructor instead | |
@JsonAutoDetect(creatorVisibility = JsonAutoDetect.Visibility.ANY) | |
public abstract class IntervalMixIn { | |
public IntervalMixIn(@JsonProperty("start") Instant startInclusive, | |
@JsonProperty("end") Instant endExclusive) { | |
} | |
} |
Here's a variation for LocalDateRange
, with a little twist to make integration into Spring Boot a tiny bit cleaner.
import java.time.LocalDate;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.threeten.extra.LocalDateRange;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
// Exclude JavaBean properties that are not part of the state
@JsonIgnoreProperties({"endInclusive", "empty", "unboundedEnd", "unboundedStart"})
@JsonAutoDetect(creatorVisibility = JsonAutoDetect.Visibility.ANY)
public abstract class LocalDateRangeMixin {
public static void applyTo(Jackson2ObjectMapperBuilder builder) {
builder.mixIn(LocalDateRange.class, LocalDateRangeMixin.class);
}
public LocalDateRangeMixin(@JsonProperty("start") LocalDate startInclusive, @JsonProperty("end") LocalDate endExclusive) { }
}
Usage in a Spring Boot @Configuration
class looks like this:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return builder -> LocalDateRangeMixin.applyTo(builder);
}
I mentioned this gist in the issue for Three Ten to implement a Jackson module.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
org.threeten.extra.Interval
cannot be serialized by Jackson. This is a mix-in that tells Jackson how to serialize / de-serializeInterval
.The mix-in is registered with Jackson as follows: