Gson缺少对象ArrayList的类型参数

时间:2016-07-04 11:58:17

标签: java android gson proguard

我有这个JSON对象,其中包含“Contact”对象列表及其子对象。我正在尝试使用gson在我的JSON对象中获取ArrayListModel对象,但它返回缺少的类型参数异常。 我得到的是这样的类型:

Type listType = new TypeToken<ArrayList<tModel>>() { }.getType();

试图获得这样的列表:

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();

ArrayList<Model> = gson.fromJson(jsonString, listType);

在我的程序中,我保留了这样的对象包:

-keep class .somerepo.contactModel.** { *; }

我见过类似的问题,但没有一个能解决我的问题。

这是stacktrace:

  

致命异常:AsyncTask#2进程:...,PID:   10360                                                                               java.lang.RuntimeException:执行时发生错误   doInBackground()       在android.os.AsyncTask $ 3.done(AsyncTask.java:300)       在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)       at java.util.concurrent.FutureTask.setException(FutureTask.java:222)       在java.util.concurrent.FutureTask.run(FutureTask.java:242)       在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)       at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)       在java.lang.Thread.run(Thread.java:841)       引起:java.lang.RuntimeException:缺少类型参数。       在com.google.gson.reflect.TypeToken.getSuperclassTypeParameter(SourceFile:84)       在com.google.gson.reflect.TypeToken。(SourceFile:62)       在semereop.contact.Contact $ 1.(SourceFile:184)       at somerepo.contact.Contact.geModelFromJson(SourceFile:184)

geModelFromJson方法从gson返回ArrayList<Model>

1 个答案:

答案 0 :(得分:6)

您必须向proguard文件添加更多信息:

# 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
-keepattributes EnclosingMethod
-keepattributes InnerClasses
-keepattributes Annotation

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

# Gson specific classes
-keep class sun.misc.Unsafe { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }

有关详细信息,请查看GSON存储库中提供的Proguard文件的this example