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

com.gocardless.http.ResponseParser Maven / Gradle / Ivy

There is a newer version: 6.0.0
Show newest version
package com.gocardless.http;

import com.gocardless.errors.ApiErrorResponse;
import com.gocardless.errors.GoCardlessApiException;
import com.gocardless.errors.GoCardlessErrorMapper;
import com.gocardless.errors.MalformedResponseException;
import com.google.common.collect.ImmutableList;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.util.List;

final class ResponseParser {
    private final Gson gson;

    ResponseParser(Gson gson) {
        this.gson = gson;
    }

     T parseSingle(String responseBody, String envelope, Class clazz) {
        JsonElement json;
        try {
            json = new JsonParser().parse(responseBody);
        } catch (JsonSyntaxException e) {
            throw new MalformedResponseException(responseBody);
        }
        JsonObject object = json.getAsJsonObject().getAsJsonObject(envelope);
        return gson.fromJson(object, clazz);
    }

     ImmutableList parseMultiple(String responseBody, String envelope,
            TypeToken> clazz) {
        JsonObject json = new JsonParser().parse(responseBody).getAsJsonObject();
        JsonArray array = json.getAsJsonArray(envelope);
        List items = gson.fromJson(array, clazz.getType());
        return ImmutableList.copyOf(items);
    }

     ImmutableList parseMultiple(JsonObject json, String envelope, TypeToken> clazz) {
        JsonArray array = json.getAsJsonArray(envelope);
        List items = gson.fromJson(array, clazz.getType());
        return ImmutableList.copyOf(items);
    }

     ListResponse parsePage(String responseBody, String envelope, TypeToken> clazz) {
        JsonObject json = new JsonParser().parse(responseBody).getAsJsonObject();
        List items = parseMultiple(json, envelope, clazz);
        JsonObject metaJson = json.getAsJsonObject("meta");
        ListResponse.Meta meta = gson.fromJson(metaJson, ListResponse.Meta.class);
        return new ListResponse<>(ImmutableList.copyOf(items), meta);
    }

    GoCardlessApiException parseError(String responseBody) {
        ApiErrorResponse error = parseSingle(responseBody, "error", ApiErrorResponse.class);
        return GoCardlessErrorMapper.toException(error);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy