Gson and Active Android: Attempted to serialize java.lang.Class. Forgot to register a type adapter?

I’m using Gson to serialize an Active Android model. The model class contains only primitives, and Gson should have no issues serializing it with the default settings. However, when I try, I get the error: java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: <MyClass>. Forgot to register a type adapter? I would really rather not write a type adapter for every one of my model classes, how can I get around this issue?

Answer:

Figured it out. Of course, Active Android’s base model class is adding fields that cannot be serialized by default. Those fields can be ignored using Gson’s excluedFieldsWithoutExposeAnnotation() option, as follows:

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

Modify the class with the @Expose annotation to indicate which fields should be serialized:

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

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

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

    ...
}

猜你喜欢

转载自blog.csdn.net/kejia90/article/details/123815188
今日推荐