Moshi Custom Adapter - IllegalArgumentException: Conflicting @FromJson methods: after gradle version raised to 5.6.4 and plugin to 3.6.0

Viewed 181

I had raised gradle version to 5.6.4 and Android Gradle plugin to 3.6.0.

I have these methods in my custom Moshi adapter:

@proguard.annotation.Keep
public static class CustomAdapters {

    @FromJson
    @NullToNone
    public double fromJsonDouble(@NonNull final JsonReader reader) throws IOException {
        if (reader.peek() == JsonReader.Token.NUMBER) {
            return reader.nextDouble();
        } else if (reader.peek() == JsonReader.Token.NULL) {
            reader.nextNull();
        }

        return NullToNone.NONE_DOUBLE;
    }

    @FromJson
    @SkipEmpty
    public double fromJsonEmptyDouble(@NonNull final JsonReader reader) throws IOException {
        return reader.nextDouble();
    }
}

     I am getting this exception. Any clue ?

  Caused by: java.lang.IllegalArgumentException: Conflicting @FromJson methods:
        public double net.abc.android.epclient.utils.MoshiFactory$CustomAdapters.fromJsonDouble(com.squareup.moshi.JsonReader) throws java.io.IOException
        public double net.abc.android.epclient.utils.MoshiFactory$CustomAdapters.fromJsonEmptyDouble(com.squareup.moshi.JsonReader) throws java.io.IOException
        at tb2$a.b(Moshi.java:42)
        at m23.a(MoshiProvider.kt:4)
        at h73.get(WebServiceModule_ProvidesMoshiFactory.java:5)
1 Answers

Both functions are annotated with @FromJson for the same input type and return type and Moshi seems to be confused which one to use for the JsonReader type. Maybe you need to remove the second and add the case for empty token, in the first function. For example:

@FromJson
@NullToNone
fun fromJsonDouble(@NonNull final JsonReader reader) : Double =  when(reader.peek()) { 
        JsonReader.Token.NUMBER  -> reader.nextDouble();
        JsonReader.Token.NULL ->  NullToNone.NONE_DOUBLE
        JsonReader.Token.STRING -> {
         // this is really undesired case where numbers are provided as strings
            val string = reader.nextString()
            if (string.isNullOrEmpty()) {
                NullToNone.NONE_DOUBLE
            } else {
                string.toDouble()
            }

        } else -> NullToNone.NONE_DOUBLE
    }

Ensure the order of cases in the when statement is preserved. The String case is optional.

Related