Created
May 4, 2020 21:32
-
-
Save chadselph/8f5ccc4c240c6d6d3cd4101ec547bcab to your computer and use it in GitHub Desktop.
jackson Deserializer.tryInOrder
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
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