Android obfuscation compilation, the use of gson-2.2.2.jar reflection parsing json data, ClassCastException error, gson parsing json
In my code, I use the following methods:
public synchronized <T> T parseJson(String json, Class<T> classOfT) throws Exception{ T target = null; Gson gson = new Gson(); target = gson.fromJson(json, classOfT); return target; }
The following method is used in my Activity:
String addModel = JsonParse. getJsonParse (). parseJson (jsonString, AddModel. class );
// Here, AddModel is a self-written model class.
// JsonString is a local file, which exists in Json format.
After compilation, the following error occurs: shortMsg: java. lang. ClassCastException.
LongMsg: java. lang. ClassCastException: com. google. gson. internal. StringMap
StackTrace: java. lang. ClassCastException: com. google. gson. internal. StringMap
At com. android. xxxx. activity. Info. c (Unknown Source)
At com. android. xxxx. activity. Info. onClick (Unknown Source)
At android. view. View. javasmclick (View. java: 2486)
At android. view. View $ custom mclick. run (View. java: 9130)
At android. OS. Handler. handleCallback (Handler. java: 587)
At android. OS. Handler. dispatchMessage (Handler. java: 92)
At android. OS. lorule. loop (lorule. java: 130)
At android. app. ActivityThread. main (ActivityThread. java: 3703)
At java. lang. reflect. Method. invokeNative (Native Method)
At java. lang. reflect. Method. invoke (Method. java: 507)
At com. android. internal. OS. ZygoteInit $ MethodAndArgsCaller. run (ZygoteInit. java: 866)
At com. android. internal. OS. ZygoteInit. main (ZygoteInit. java: 624)
At dalvik. system. nativeStart. main (Native Method) is a solution that uses Gson reflection to parse json strings. After obfuscation, the member variables of the Model change, resulting in the member variable name not matching the json string: in proguard. in the cfg file, we first declare that we should not confuse the corresponding Model class, for example, AddModel:
-keep public class com.android.chebaob.model.AddModel{ *;}
In addition, add the following content at the end of the proguard. cfg file:
##---------------Begin: proguard configuration for Gson ----------# 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.** { *; }##---------------End: proguard configuration for Gson ----------
This will solve the problem.
How to Use gson-222jar, I want to use Gson to parse json Sina Weibo data, kneeling pointing
Www.ostools.net/apidocs/apidoc? Api = gson2.2.2
Reading documents