All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.dft.api.shopify.handler.JsonBodyHandler Maven / Gradle / Ivy

The newest version!
package com.dft.api.shopify.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);
                    }
                });
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy