| 31 | import java.util.Collections; |
| 32 | |
| 33 | public class GsonDecoder implements Decoder, JsonDecoder { |
| 34 | |
| 35 | private final Gson gson; |
| 36 | |
| 37 | public GsonDecoder(Iterable<TypeAdapter<?>> adapters) { |
| 38 | this(GsonFactory.create(adapters)); |
| 39 | } |
| 40 | |
| 41 | public GsonDecoder() { |
| 42 | this(Collections.<TypeAdapter<?>>emptyList()); |
| 43 | } |
| 44 | |
| 45 | public GsonDecoder(Gson gson) { |
| 46 | this.gson = gson; |
| 47 | } |
| 48 | |
| 49 | @Override |
| 50 | public Object decode(Response response, Type type) throws IOException { |
| 51 | if (response.status() == 404 || response.status() == 204) return Util.emptyValueOf(type); |
| 52 | if (response.body() == null) return null; |
| 53 | Reader reader = response.body().asReader(UTF_8); |
| 54 | try { |
| 55 | return gson.fromJson(reader, type); |
| 56 | } catch (JsonIOException e) { |
| 57 | if (e.getCause() != null && e.getCause() instanceof IOException) { |
| 58 | throw IOException.class.cast(e.getCause()); |
| 59 | } |
| 60 | throw e; |
| 61 | } finally { |
| 62 | ensureClosed(reader); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | @Override |
| 67 | public Object convert(Object object, Type type) { |
| 68 | return gson.fromJson(gson.toJsonTree(object), type); |
| 69 | } |
| 70 | } |
nothing calls this directly
no outgoing calls
no test coverage detected