Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 253
GLee Avatar asked Apr 28 '15 00:04

GLee


2 Answers

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;

    ...
}
like image 58
GLee Avatar answered Nov 19 '22 14:11

GLee


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();
like image 44
mehdi Avatar answered Nov 19 '22 13:11

mehdi