简体   繁体   中英

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 ?

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

如果TimestampAdapter在Gson中为Timestamp类注册,则JsonSerializationContext应自动使用它来序列化对象并返回JsonElement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM