其他分享
首页 > 其他分享> > Gson 实体类解析问题

Gson 实体类解析问题

作者:互联网

混淆规则(解决Relase包无法正常解析)

# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-keep class sun.misc.Unsafe { *; }
//这里很重要不可忽略
-keep class com.google.gson.stream.** { *; }

#实体类跳过混淆
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
//这里是自定义的实体类
-keep class com.xxx.bean.** { *; }
-keep class com.xxx.bean.*

Type (解决 gson cannot be cast to xxx 问题)

//两种方法获取Type
1 如果是确定的实体类型就用这种
Type type = new TypeToken<A>() {}.getType();
Gson().fromJson(data, type)

2 如果是带有泛型类型的解析就用这种
Type type = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Gson().fromJson(data, type)

标签:实体类,Type,class,keep,com,解析,type,Gson
来源: https://blog.csdn.net/qq_39140369/article/details/122212645