|
| 1 | +package com.fasterxml.jackson.datatype.guava.deser; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonParseException; |
| 4 | +import com.fasterxml.jackson.core.JsonParser; |
| 5 | +import com.fasterxml.jackson.databind.BeanProperty; |
| 6 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 7 | +import com.fasterxml.jackson.databind.JavaType; |
| 8 | +import com.fasterxml.jackson.databind.JsonDeserializer; |
| 9 | +import com.google.common.collect.ImmutableRangeSet; |
| 10 | +import com.google.common.collect.Range; |
| 11 | +import com.google.common.collect.RangeSet; |
| 12 | + |
| 13 | +import java.io.IOException; |
| 14 | +import java.util.List; |
| 15 | + |
| 16 | +public class RangeSetDeserializer extends JsonDeserializer<RangeSet<Comparable<?>>> { |
| 17 | + private JavaType genericRangeListType; |
| 18 | + |
| 19 | + @Override |
| 20 | + public RangeSet<Comparable<?>> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { |
| 21 | + if (genericRangeListType == null) { |
| 22 | + throw new JsonParseException(p, "RangeSetJsonSerializer was not contextualized (no deserialize target type). " + |
| 23 | + "You need to specify the generic type down to the generic parameter of RangeSet."); |
| 24 | + } else { |
| 25 | + @SuppressWarnings("unchecked") final Iterable<Range<Comparable<?>>> ranges |
| 26 | + = (Iterable<Range<Comparable<?>>>) ctxt |
| 27 | + .findContextualValueDeserializer(genericRangeListType, null).deserialize(p, ctxt); |
| 28 | + ImmutableRangeSet.Builder<Comparable<?>> builder = ImmutableRangeSet.builder(); |
| 29 | + for (Range<Comparable<?>> range : ranges) { |
| 30 | + builder.add(range); |
| 31 | + } |
| 32 | + return builder.build(); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) { |
| 38 | + final JavaType genericType = ctxt.getContextualType().containedType(0); |
| 39 | + if (genericType == null) return this; |
| 40 | + final RangeSetDeserializer deserializer = new RangeSetDeserializer(); |
| 41 | + deserializer.genericRangeListType = ctxt.getTypeFactory().constructCollectionType(List.class, |
| 42 | + ctxt.getTypeFactory().constructParametricType(Range.class, genericType)); |
| 43 | + return deserializer; |
| 44 | + } |
| 45 | +} |
0 commit comments