Skip to content

Instantly share code, notes, and snippets.

@chadselph
Created May 4, 2020 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadselph/8f5ccc4c240c6d6d3cd4101ec547bcab to your computer and use it in GitHub Desktop.
Save chadselph/8f5ccc4c240c6d6d3cd4101ec547bcab to your computer and use it in GitHub Desktop.
jackson Deserializer.tryInOrder
package com.goswiftly.services.gtfspoller.jacksonutil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import io.vavr.control.Try;
import java.util.NoSuchElementException;
public class Deserializers {
/**
* Makes a new json deserializer that tries the delegates in order. Returns the first one that was
* successful or throws the last one's exception
*/
public static <T> JsonDeserializer<T> tryInOrder(JsonDeserializer<? extends T>... delegates) {
return new JsonDeserializer<T>() {
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) {
Try<? extends T> thisTry = Try.failure(new NoSuchElementException());
// Basically Try.sequence but succeed for one success instead of fail for one error
for (JsonDeserializer<? extends T> d : delegates) {
thisTry = Try.of(() -> d.deserialize(p, ctxt));
if (thisTry.isSuccess()) {
return thisTry.get();
}
}
return thisTry.get(); // throws the last exception
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment