Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize moshi decoding #2183

Merged
merged 4 commits into from
Sep 30, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 7 additions & 17 deletions moshi/src/main/java/feign/moshi/MoshiDecoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,16 @@
*/
package feign.moshi;

import com.google.common.io.CharStreams;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also remove the guava dependency from pom?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, done in f3cd4d8

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonDataException;
import com.squareup.moshi.JsonEncodingException;
import com.squareup.moshi.Moshi;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import okio.BufferedSource;
import okio.Okio;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import static feign.Util.UTF_8;
import static feign.Util.ensureClosed;

public class MoshiDecoder implements Decoder {
private final Moshi moshi;
Expand All @@ -42,7 +39,6 @@ public MoshiDecoder(Iterable<JsonAdapter<?>> adapters) {
this(MoshiFactory.create(adapters));
}


@Override
public Object decode(Response response, Type type) throws IOException {
JsonAdapter<Object> jsonAdapter = moshi.adapter(type);
Expand All @@ -52,23 +48,17 @@ public Object decode(Response response, Type type) throws IOException {
if (response.body() == null)
return null;

Reader reader = response.body().asReader(UTF_8);

try {
return parseJson(jsonAdapter, reader);
try (BufferedSource source = Okio.buffer(Okio.source(response.body().asInputStream()))) {
if (source.exhausted()) {
return null; // empty body
}
return jsonAdapter.fromJson(source);
} catch (JsonDataException e) {
if (e.getCause() != null && e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
throw e;
} finally {
ensureClosed(reader);
}
}

private Object parseJson(JsonAdapter<Object> jsonAdapter, Reader reader) throws IOException {
String targetString = CharStreams.toString(reader);
return jsonAdapter.fromJson(targetString);
}
}