com.gocardless.http.ResponseParser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gocardless-pro Show documentation
Show all versions of gocardless-pro Show documentation
Client library for accessing the GoCardless Pro API
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