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

11,128

Solution 1

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;

    ...
}

Solution 2

an easier way is to initialize your Gson as below to prevent serializing Final,Transient or Static fields

Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .serializeNulls()
            .create();
Share:
11,128
GLee
Author by

GLee

Updated on June 07, 2022

Comments

  • GLee
    GLee about 2 years

    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?