Last active
February 1, 2025 14:52
-
-
Save billybong/0b2963c85912f4a2ee7b591dd85a93b6 to your computer and use it in GitHub Desktop.
JacksonBodyHandler for parsing JSON responses directly from Java 11+ http clients
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 com.fasterxml.jackson.core.type.TypeReference; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import java.io.IOException; | |
import java.io.UncheckedIOException; | |
import java.net.http.HttpResponse; | |
import java.util.function.Function; | |
public class JacksonBodyHandlers { | |
private final ObjectMapper objectMapper; | |
public JacksonBodyHandlers(ObjectMapper objectMapper) { | |
this.objectMapper = objectMapper; | |
} | |
public HttpResponse.BodyHandler<JsonNode> jsonNodeHandler(){ | |
return responseInfo -> subscriberFrom(objectMapper::readTree); | |
} | |
public <T> HttpResponse.BodyHandler<T> handlerFor(TypeReference<T> typeReference){ | |
return responseInfo -> subscriberFrom((bytes) -> objectMapper.readValue(bytes, typeReference)); | |
} | |
public <T> HttpResponse.BodyHandler<T> handlerFor(Class<T> clazz){ | |
return responseInfo -> subscriberFrom((bytes) -> objectMapper.readValue(bytes, clazz)); | |
} | |
private <T> HttpResponse.BodySubscriber<T> subscriberFrom(IOFunction<byte[], T> ioFunction) { | |
return HttpResponse.BodySubscribers.mapping(HttpResponse.BodySubscribers.ofByteArray(), rethrowRuntime(ioFunction)); | |
} | |
@FunctionalInterface | |
interface IOFunction<V, T> { | |
T apply(V value) throws IOException; | |
} | |
private static <V,T> Function<V,T> rethrowRuntime(IOFunction<V, T> ioFunction){ | |
return (V v) -> { | |
try{ | |
return ioFunction.apply(v); | |
} catch (IOException e) { | |
throw new UncheckedIOException(e); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@billybong doing gods work thank you mate