Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke another serializer from a custom Gson JsonSerializer?

I have my custom class User:

class User {
    public String name;
    public int id;
    public Address address;
    public Timestamp created;
}

I'm now creating a custom JsonSerializer for User.class:

@Override
public JsonElement serialize(User src, Type typeOfSrc,
        JsonSerializationContext context) {
    JsonObject obj = new JsonObject();
    obj.addProperty("name", src.name);
    obj.addProperty("id", src.id);
    obj.addProperty("address", src.address.id);

    // Want to invoke another JsonSerializer (TimestampAdapter) for Timestamp   
    obj.add("created", ???);
    return obj;
}

But I already have a TimestampAdapter that I use for Timestamp.class. How can I invoke this JsonSerializer to be used on the "created"-field in User.class?

like image 996
Jonas Avatar asked May 18 '11 20:05

Jonas


1 Answers

obj.add("created", context.serialize(src.created));

If your TimestampAdapter is registered with Gson for the Timestamp class, the JsonSerializationContext should automatically use it to serialize the object and return a JsonElement.

like image 139
ColinD Avatar answered Oct 30 '22 10:10

ColinD