如何让 proguard 为对象保留 kotlinx 序列化程序?

How to make proguard keep kotlinx serializers for objects?

我有一个 kotlin class 和一个对象


@Serializable
@SerialName("Cl")
class Cl(...)

@Serializable
@SerialName("Obj")
object Obj

我的混淆器是这样配置的

-keepclassmembers class kotlinx.serialization.json.** {
    *** Companion;
}
-keepclasseswithmembers class kotlinx.serialization.json.** {
    kotlinx.serialization.KSerializer serializer(...);
}
-keepclasseswithmembers class .** {
    kotlinx.serialization.KSerializer serializer(...);
}

-keep,includedescriptorclasses class my.package.**$$serializer { *; }

但是,虽然 class 的序列化器被保留,但对象的序列化器没有。 这是 class:

的映射
Cl -> Cl:
...
    ...
    67:67:void <init>(... ,kotlinx.serialization.internal.SerializationConstructorMarker) -> <init>
    70:75:void <init>(...) -> <init>
    67:67:void write$Self(Cl,kotlinx.serialization.encoding.CompositeEncoder,kotlinx.serialization.descriptors.SerialDescriptor) -> e
Cl$$serializer -> Cl$$serializer:
...
    67:75:void <clinit>() -> <clinit>
    67:67:void <init>() -> <init>
    67:67:kotlinx.serialization.KSerializer[] childSerializers() -> childSerializers
    67:67:Cl deserialize(kotlinx.serialization.encoding.Decoder) -> deserialize
    67:67:java.lang.Object deserialize(kotlinx.serialization.encoding.Decoder) -> deserialize
    67:67:void serialize(kotlinx.serialization.encoding.Encoder,Cl) -> serialize
    67:67:void serialize(kotlinx.serialization.encoding.Encoder,java.lang.Object) -> serialize
    67:67:kotlinx.serialization.KSerializer[] typeParametersSerializers() -> typeParametersSerializers
Cl$Companion -> Cl$Companion:
...
    67:67:void <init>() -> <init>
    67:67:kotlinx.serialization.KSerializer serializer() -> serializer

这里是对象的映射:

Obj -> Obj:
...
    Obj INSTANCE -> n
    kotlin.Lazy $cachedSerializer$delegate -> o
    ...
    47:47:kotlin.Lazy get$cachedSerializer$delegate() -> e
    47:47:kotlinx.serialization.KSerializer serializer() -> serializer
Obj$$cachedSerializer$delegate -> Obj$a:
...
    Obj$$cachedSerializer$delegate INSTANCE -> l
    47:47:kotlinx.serialization.KSerializer invoke() -> a
    47:47:java.lang.Object invoke() -> m
...

这种混淆会在使用时导致崩溃(仅当混淆时,仅针对对象):

polymorphic(...) {
  subclass(Obj::class)
}

Serializer for class 'Obj' is not found. Mark the class as @Serializable or provide the serializer explicitly.

我如何告诉 Proguard 将序列化程序保留 object 秒?

有可用的文档 on how to configure ProGuard,它似乎与您正在使用的配置不匹配。

使用它,您就可以开始了。

纯粹是信息性的,因为上面已经回答了你的问题:object 的运行时序列化程序查找是不同的,并且发生在 INSTANCE。文档中的相关部分。

# Keep `INSTANCE.serializer()` of serializable objects.
-if @kotlinx.serialization.Serializable class ** {
    public static ** INSTANCE;
}
-keepclassmembers class <1> {
    public static <1> INSTANCE;
    kotlinx.serialization.KSerializer serializer(...);
}