2011-05-18 13 views
13

我有我的自定義類User如何從定製的Gson JsonSerializer調用另一個序列化程序?

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

我現在創建一個自定義JsonSerializer爲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; 
} 

,但我已經有一個TimestampAdapter,我使用的Timestamp.class。我如何調用JsonSerializer用於User.class的「創建」字段?

回答

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

如果TimestampAdapter與GSON註冊了Timestamp班,JsonSerializationContext應自動使用它來序列化對象,並返回一個JsonElement