Ced Ced - 1 year ago 105
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

. That works. In this team I have a list of
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

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

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

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

public class UserData{
public Team team;

This is the custom serializer where I cannot add the property

public class TeamSerializer implements JsonSerializer<Team>{
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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download