Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top