From d6eac54ccfa69220f7a3b78c391ec336e9bedf46 Mon Sep 17 00:00:00 2001 From: Jake Wharton Date: Wed, 27 Mar 2024 10:45:03 -0400 Subject: [PATCH] Make optional converter public --- CHANGELOG.md | 2 +- .../retrofit2/OptionalConverterFactory.java | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 511a9e0516..ce0e77c017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ **Changed** - - Nothing yet! + - The built-in `OptionalConverterFactory` is now public to allow installing it before other converters which consume all types (e.g., Moshi, Gson, Jackson, etc.). **Fixed** diff --git a/retrofit/src/main/java/retrofit2/OptionalConverterFactory.java b/retrofit/src/main/java/retrofit2/OptionalConverterFactory.java index 4c628b7c7c..6d50c83e32 100644 --- a/retrofit/src/main/java/retrofit2/OptionalConverterFactory.java +++ b/retrofit/src/main/java/retrofit2/OptionalConverterFactory.java @@ -25,9 +25,24 @@ import okhttp3.ResponseBody; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; +/** + * A {@link Converter.Factory} which supports Java's {@link Optional} to wrap null values from + * another converter. + *

+ * This factory is installed by default on the JVM and Android API 24+. If you are using another + * converter which tries to serialize all types, such as Moshi or Gson, the default installation + * of this factory never gets a chance to run. To work around this, you can explicitly install this + * factory before your serialization library converter. + */ @IgnoreJRERequirement // Only added when Optional is available (Java 8+ / Android API 24+). @TargetApi(24) -final class OptionalConverterFactory extends Converter.Factory { +public final class OptionalConverterFactory extends Converter.Factory { + public static OptionalConverterFactory create() { + return new OptionalConverterFactory(); + } + + OptionalConverterFactory() {} + @Override public @Nullable Converter responseBodyConverter( Type type, Annotation[] annotations, Retrofit retrofit) { @@ -43,7 +58,7 @@ final class OptionalConverterFactory extends Converter.Factory { @IgnoreJRERequirement static final class OptionalConverter implements Converter> { - final Converter delegate; + private final Converter delegate; OptionalConverter(Converter delegate) { this.delegate = delegate;