【问题标题】:Gson missing type parameter for ArrayList of objectsGson 缺少对象 ArrayList 的类型参数
【发布时间】:2016-11-06 03:44:24
【问题描述】:

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

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

并试图得到这样的列表:

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

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

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

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

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

这是堆栈跟踪:

致命异常:AsyncTask #2 进程:...,PID: 10360 java.lang.RuntimeException:执行时发生错误 做背景() 在 android.os.AsyncTask$3.done(AsyncTask.java:300) 在 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 在 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) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 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) 在 somerepo.contact.Contact.geModelFromJson(SourceFile:184)

geModelFromJson 方法从 gson 返回 ArrayList&lt;Model&gt;

【问题讨论】:

  • 请分享完整的堆栈跟踪
  • @sidgate 我更新了帖子:)
  • 你能发布你的模型和你试图转换的字符串吗?

标签: java android gson proguard


【解决方案1】:

您必须在您的 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

【讨论】:

  • 只是添加到这个答案:使用默认 proguard 配置时只需要 -keepattributes 签名。
  • 只需要 -keepattributes 签名并为我工作
猜你喜欢
  • 2016-06-13
  • 1970-01-01
  • 2017-03-25
  • 2011-12-29
  • 2017-10-30
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多