vendredi 5 mai 2017

GSON Custom serialization with annotations

I have a very specific case of custom serialization with GSON:

Let's say I have a following class:

public class Student extends BaseModel{
    private int id;
    private String name;
    private Student goodFriend;
    private Student bestFriend;
}

BaseModel is just a base class for all my model classes.

When I simply do

gson.toJson(student /* Some Student instance */);

I will get for example:

{
 id: 1, 
 name: "Jack", 
 goodFriend: {id: 2, name: "Matt"}, 
 bestFriend: {id: 3, name "Tom"}
}

It's fine, but what I need is this:

{
 id: 1, 
 name: "Jack", 
 goodFriend: 2, // only an ID for this field
 bestFriend: {id: 3, name "Tom"} // whole object for this field
 // both fields are of the same Type, so I can't use TypeAdapterFactory for this
}

I need some way of marking the fields with serialization type (id or object) and then using that marking to serialize as needed. How do I do that in general, not just for a Student class, but for all subclasses of BaseModel?

My only idea was to use custom annotations: describing the fields that I want to serialize as ID only with one annotation, and fields that I want to serialize as objects with another annotation, but I couldn't find a way to retrieve the annotations in TypeAdapter's write method.

Any ideas how to handle this?





Aucun commentaire:

Enregistrer un commentaire