17

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?

GLee
  • 5,003
  • 5
  • 35
  • 39

2 Answers2

24

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;

    ...
}
GLee
  • 5,003
  • 5
  • 35
  • 39
  • Where to set Gson setting in application for ActiveAndroid like Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); – ahmadalibaloch Apr 15 '16 at 12:56
15

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();
mehdi
  • 912
  • 7
  • 20
  • This is perfect solution. Above solutions make "mId" null so model.delete(); causes null pointer exception. – Vaibhav Jani Sep 23 '15 at 06:24
  • Where to set Gson setting in application for ActiveAndroid like Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); – ahmadalibaloch Apr 15 '16 at 12:56
  • I am getting the following error after following the GLee's approach. Did anyone else get this: Failed to invoke public consturctor with no args – AmrataB May 04 '16 at 05:44
  • @AmrataB This error is raised when you did not create a no-argument constructor for the class you are serializing. – Stéphane Jun 06 '16 at 20:29
  • @medhi Unclear whether the Gson can/should be used as a singleton, or the GsonBuilder().. should be (and reused to .create() ). Is the Gson reusable? – Dave Pullin Jan 18 '17 at 14:33