Moshi: Obfuscation and enums

Created on 25 Sep 2018  路  6Comments  路  Source: square/moshi

The integrated EnumJsonAdapter in StandardJsonAdapters can't be instantiated because the field name doesn't match the name anymore.

My solution is to annotate enums that are used with Moshi with @JsonClass(generateAdapter = false) and then keep the field names for annotated enums:

-keepclassmembernames @com.squareup.moshi.JsonClass class * extends java.lang.Enum {
    <fields>;
}

This way it's possible to avoid keeping all enums.

Do you think it would make sense to add it to the shipped Proguard config?

Most helpful comment

@ezamelczykespeo Issue probably resides in this line:

https://github.com/square/moshi/blob/master/moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java#L240

The Java method getEnumConstants() still gives back the literal enum names, not the obfuscated ones, so initializing Moshi with any enum adapter will crash with an AssertionError that wraps a NoSuchFieldException stemming from the failed reflection call.

All 6 comments

Yeah, I like that.

Does that mean that enums will only work with moshi if they're annotated with @JsonClass(generateAdapter = false)?

If you're using proguard/R8 and they would rename or remove one of the enum fields, yes.

I don't understand why @Json(name = "name) isn't sufficient. Enums work with Gsons @SerializedName

@ezamelczykespeo Issue probably resides in this line:

https://github.com/square/moshi/blob/master/moshi/src/main/java/com/squareup/moshi/StandardJsonAdapters.java#L240

The Java method getEnumConstants() still gives back the literal enum names, not the obfuscated ones, so initializing Moshi with any enum adapter will crash with an AssertionError that wraps a NoSuchFieldException stemming from the failed reflection call.

@gabrielittner you just saved my day. 馃檱

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Speedrockracer picture Speedrockracer  路  4Comments

PaulWoitaschek picture PaulWoitaschek  路  4Comments

feinstein picture feinstein  路  4Comments

cdongieux picture cdongieux  路  4Comments

ayedo picture ayedo  路  4Comments