Jackson + ProGuard:无法反序列化使用自定义反序列化程序的类

时间:2016-03-08 20:38:00

标签: jackson proguard

我的应用使用杰克逊。我得到了最小化的构建,主要是使用这种配置:

# don't obfuscate Jackson classes
-keep class com.fasterxml.** { *; }

# don't strip runtime annotations
-keepattributes RuntimeVisibleAnnotations

# keep members with Jackson annotations
-keepclassmembers public class * {
     @com.fasterxml.jackson.annotation.JsonCreator *;
     @com.fasterxml.jackson.annotation.JsonProperty *;
}

但是,最小化的构建仍然无法反序列化使用自定义反序列化器的一个类,而后者又使用工厂。工厂,反序列化器和映射器都是由Dagger2生产的。错误是:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.mycompany.myapp.c.y]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
            at [Source: N/A; line: -1, column: -1]
            at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(Unknown Source)
            at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(Unknown Source)
            at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(Unknown Source)
            at com.fasterxml.jackson.databind.ObjectMapper._readValue(Unknown Source)
            at com.fasterxml.jackson.databind.ObjectMapper.readValue(Unknown Source)
            at com.fasterxml.jackson.databind.ObjectMapper.treeToValue(Unknown Source)
            at com.mycompany.myapp.c.x.a(Unknown Source)
            at com.mycompany.myapp.c.x.a(Unknown Source)
            at com.mycompany.myapp.c.x.deserialize(Unknown Source)
            at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(Unknown Source)
            at com.fasterxml.jackson.databind.ObjectMapper.readValue(Unknown Source)
            at com.mycompany.myapp.c.ag.d(Unknown Source)
            at com.mycompany.myapp.c.ag.a(Unknown Source)
            at com.mycompany.myapp.c.at.run(Unknown Source)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4508)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
            at dalvik.system.NativeStart.main(Native Method)

错误消息表明我的类缺少默认构造函数,实际上它确实是因为实例是由自定义反序列化程序使用工厂创建的。当我禁用ProGuard时,这很好用。我需要做些什么才能使其与ProGuard一起使用?

1 个答案:

答案 0 :(得分:2)

我偶然发现了这种方便的故障排除技术:

-keepnames class * { *; }

这揭示了在我的自定义反序列化器中成为私有静态嵌套类的真正罪魁祸首。解决方案是从此选项的类说明符中删除public

-keepclassmembers class * {
     @com.fasterxml.jackson.annotation.JsonCreator *;
     @com.fasterxml.jackson.annotation.JsonProperty *;
}