gpt4 book ai didi

android - Gson 和 Active Android : Attempted to serialize java. lang.Class。忘记注册类型适配器?

转载 作者:IT老高 更新时间:2023-10-28 23:29:36 33 4
gpt4 key购买 nike

我正在使用 Gson 序列化一个 Active Android 模型。模型类只包含原语,Gson 使用默认设置序列化它应该没有问题。但是,当我尝试时,我得到了错误:

java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: <MyClass>. Forgot to register a type adapter?

我真的不想为我的每个模型类编写一个类型适配器,我该如何解决这个问题?

最佳答案

想通了。当然,Active Android 的基础模型类是添加了默认不能序列化的字段。可以使用 Gson 的 excluedFieldsWithoutExposeAnnotation() 选项忽略这些字段,如下所示:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(new Book());

@Expose注解修改类,指明哪些字段应该被序列化:

@Table(name = "Foo")
public class Foo extends Model {

@Expose
@Column(name = "Name")
public String name;

@Expose
@Column(name = "Sort")
public int sort;

...
}

关于android - Gson 和 Active Android : Attempted to serialize java. lang.Class。忘记注册类型适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29908128/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com