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 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); | |
} | |
}; | |
} | |
} |
Small hint how to use, knowing that we can block exec thread:
https://docs.oracle.com/en/java/javase/13/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#mapping(java.net.http.HttpResponse.BodySubscriber,java.util.function.Function)
@billybong doing gods work thank you mate
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple utility class for leveraging Jackson to parse Http responses from the standard Java 11+ http client.
Oh god how I wish the JDK came with native JSON support...