Ced Ced - 1 month ago 9
Java Question

gson nested custom serializer

I've a nested object that I cannot manage to serialize with gson. I made a custom serializer which is used with the parent object but with the child one I didn't manage to make it work.

So in my code below the custom serializer is used to serialize a

Team
. That works. In this team I have a list of
User
that I want to serialize as well. Unfortunately the method
addProperty(String a, String b)
askes for 2 strings (or a primitive) so I cannot add a property members which is of the class
User
.

Here is the code, first I create a
Gson
object and register the custom serializer for
Team
:

gson = new GsonBuilder().registerTypeAdapter(Team.class, new TeamSerializer())
.create();
gson.toJson(userData); // UserData instance.


This is the class that is gonna be serialized with the
Gson
object (I omitted irrelevant fields symbolized by //...):

public class UserData{
public Team team;
//...
}


This is the custom serializer where I cannot add the property
members
:

public class TeamSerializer implements JsonSerializer<Team>{
@Override
public JsonElement serialize(Team src, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("id", src.getIdteams());
object.addProperty("name", src.getName());
object.addProperty("tag", src.getTag());
object.addProperty("picture", src.getProfilePic());
//object.addProperty("members", src.getMembers());
return object;
}
}


This is the
Team
class:

public class Team implements Serializable {
private long idteams;
private String name;
private String tag;
private String profilePic;
private List<User> members;
//...
}

Answer

Describe the generic relationships with TypeToken and use the context to transform the list:

TypeToken<List<User>> typeDescription = new TypeToken<List<User>>() {};
JsonElement members = context.serialize(src.getMembers(), typeDescription);
object.addProperty("members", members);

If User isn't a standard bean you may need a TypeAdapter for it too.