13

我有我的自定义课程User

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

我现在正在为 User.class 创建一个自定义 JsonSerializer:

@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;
}

但我已经有一个TimestampAdapter用于Timestamp.class. 如何调用它JsonSerializer以在“创建”字段中使用User.class

4

1 回答 1

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

如果您TimestampAdapter已为Timestamp该类注册了 Gson,JsonSerializationContext则应自动使用它来序列化对象并返回一个JsonElement.

于 2011-05-18T21:00:34.357 回答