android - Moshi Json 注释不适用于 proguard
问题描述
我按照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 的一些东西,但我真的不知道它是什么
解决方案
尝试添加:
@JsonClass(generateAdapter = false)
并将这些行添加到 proguard :
-keepclassmembernames @com.squareup.moshi.JsonClass class * extends java.lang.Enum {
<fields>;
}
推荐阅读
- javascript - 为什么我们需要在这个例子中使用 THIS 关键字?
- reactjs - 如何在卸载 React 模式登录组件之前更新本地存储值
- python - 在python的setter中调用方法
- laravel - 在 Eloquent 中使用 orWhere()
- reactjs - 使用 Thunk 将数据从 Redux 存储加载到 React 状态
- ios - IOS应用程序即使根本不工作也能做事吗(Killed/Non-running state)
- android - 在实时布局检查器中手动选择活动(Android Studio 4.0)
- c++ - 命名空间 std:: 不包含可选
- node.js - firebase,我如何根据用户 ID 获得特定结构
- junit - Jigsaw 从测试中读取资源