io.github.dft.amazon.model.handler.JsonBodyHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of amazon-sp-api Show documentation
Show all versions of amazon-sp-api Show documentation
Amazon SP API using JDK 11
package io.github.dft.amazon.model.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class JsonBodyHandler implements HttpResponse.BodyHandler {
private Class wClass;
public JsonBodyHandler(Class wClass) {
this.wClass = wClass;
}
@Override
public HttpResponse.BodySubscriber apply(HttpResponse.ResponseInfo responseInfo) {
return asJSON(wClass);
}
public static HttpResponse.BodySubscriber asJSON(Class targetType) {
HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8);
return HttpResponse.BodySubscribers.mapping(
upstream,
(String body) -> {
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(body, targetType);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}