|
| 1 | +/* |
| 2 | + * Copyright 2012-2023 The Feign Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | + * in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | + * or implied. See the License for the specific language governing permissions and limitations under |
| 12 | + * the License. |
| 13 | + */ |
| 14 | +package feign.moshi; |
| 15 | + |
| 16 | +import com.google.common.io.CharStreams; |
| 17 | +import com.squareup.moshi.JsonAdapter; |
| 18 | +import com.squareup.moshi.JsonDataException; |
| 19 | +import com.squareup.moshi.JsonEncodingException; |
| 20 | +import com.squareup.moshi.Moshi; |
| 21 | +import feign.Response; |
| 22 | +import feign.Util; |
| 23 | +import feign.codec.Decoder; |
| 24 | +import java.io.IOException; |
| 25 | +import java.io.Reader; |
| 26 | +import java.lang.reflect.Type; |
| 27 | +import static feign.Util.UTF_8; |
| 28 | +import static feign.Util.ensureClosed; |
| 29 | + |
| 30 | +public class MoshiDecoder implements Decoder { |
| 31 | + private final Moshi moshi; |
| 32 | + |
| 33 | + public MoshiDecoder(Moshi moshi) { |
| 34 | + this.moshi = moshi; |
| 35 | + } |
| 36 | + |
| 37 | + public MoshiDecoder() { |
| 38 | + this.moshi = new Moshi.Builder().build(); |
| 39 | + } |
| 40 | + |
| 41 | + public MoshiDecoder(Iterable<JsonAdapter<?>> adapters) { |
| 42 | + this(MoshiFactory.create(adapters)); |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + @Override |
| 47 | + public Object decode(Response response, Type type) throws IOException { |
| 48 | + JsonAdapter<Object> jsonAdapter = moshi.adapter(type); |
| 49 | + |
| 50 | + if (response.status() == 404 || response.status() == 204) |
| 51 | + return Util.emptyValueOf(type); |
| 52 | + if (response.body() == null) |
| 53 | + return null; |
| 54 | + |
| 55 | + Reader reader = response.body().asReader(UTF_8); |
| 56 | + |
| 57 | + try { |
| 58 | + return parseJson(jsonAdapter, reader); |
| 59 | + } catch (JsonDataException e) { |
| 60 | + if (e.getCause() != null && e.getCause() instanceof IOException) { |
| 61 | + throw (IOException) e.getCause(); |
| 62 | + } |
| 63 | + throw e; |
| 64 | + } finally { |
| 65 | + ensureClosed(reader); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + private Object parseJson(JsonAdapter<Object> jsonAdapter, Reader reader) throws IOException { |
| 70 | + String targetString = CharStreams.toString(reader); |
| 71 | + return jsonAdapter.fromJson(targetString); |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments