Skip to content

Instantly share code, notes, and snippets.

@bcalmac
Last active August 18, 2021 21:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcalmac/4c426f3155ef6d93fe985600ab169883 to your computer and use it in GitHub Desktop.
Save bcalmac/4c426f3155ef6d93fe985600ab169883 to your computer and use it in GitHub Desktop.
Jackson serialization for Interval
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) {
}
}
@bcalmac
Copy link
Author

bcalmac commented Feb 19, 2018

org.threeten.extra.Interval cannot be serialized by Jackson. This is a mix-in that tells Jackson how to serialize / de-serialize Interval.The mix-in is registered with Jackson as follows:

objectMapper.addMixIn(Interval.class, IntervalMixIn.class);

@erizzo
Copy link

erizzo commented Aug 18, 2021

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);
}

@erizzo
Copy link

erizzo commented Aug 18, 2021

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