问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/6050869/how-to-invoke-another-serializer-from-a-custom-gson-jsonserializer