【问题标题】:Moshi Json annotation does not work with proguardMoshi Json 注释不适用于 proguard
【发布时间】:2020-05-26 16:55:15
【问题描述】:

我跟着https://github.com/square/moshi添加了对moshi和proguard规则的gradle依赖,然后我写代码来验证。

data class Car(
    @Json(name = "low_speed")  val lowSpeed: Int,
    @Json(name = "high_speed") val highSpeed: Int
)
val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
val jsonAdapter = moshi.adapter(Car::class.java)

val json = "{\"low_speed\": 10, \"high_speed\": 20}"
val car = jsonAdapter.fromJson(json)

if (car != null) {
    Toast.makeText(this, "${car.lowSpeed}+${car.highSpeed}", Toast.LENGTH_LONG).show()
}

当我在调试模式下运行它时,它显示“10+20”,这是预期的,但是当我在发布模式下运行(启用了 proguard)时,我看到了“0+0”。

我的 proguard-rules.pro 文件:

# Retain generic type information for use by reflection by converters     and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions

# Common Stuff to Keep
-keepattributes *Annotation*
-keepattributes JavascriptInterface

# OkHttp
-dontwarn javax.annotation.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn okhttp3.internal.platform.ConscryptPlatform

# okIo
-dontwarn okio.**

#moshi
# JSR 305 annotations are for embedding nullability information.
-keepclasseswithmembers class * {
    @com.squareup.moshi.* <methods>;
}

-keep @com.squareup.moshi.JsonQualifier interface *

# Enum field names are used by the integrated EnumJsonAdapter.
# values() is synthesized by the Kotlin compiler and is used by EnumJsonAdapter indirectly
# Annotate enums with @JsonClass(generateAdapter = false) to use them with Moshi.
-keepclassmembers @com.squareup.moshi.JsonClass class * extends java.lang.Enum {
    <fields>;
    **[] values();
}

#moshi-kotlin
-keep class kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoaderImpl

-keepclassmembers class kotlin.Metadata {
    public <methods>;
}

我的 build.gradle 依赖:

// moshi
implementation("com.squareup.moshi:moshi:1.9.2")
implementation("com.squareup.moshi:moshi-kotlin:1.9.2")

// okhttp
implementation "com.squareup.okhttp3:okhttp:3.10.0"

我想我缺少 moshi 和 proguard 的一些东西,但我真的不知道它是什么

【问题讨论】:

  • 你能分享你的模块gradle文件吗
  • 您最终找到解决方案了吗?我遇到了类似的问题。

标签: android json moshi


【解决方案1】:

尝试添加:

@JsonClass(generateAdapter = false)

AND 将这些行添加到 proguard:

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

信用 -> https://github.com/square/moshi/issues/689

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2021-11-06
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多