简体   繁体   English

如何从自定义Gson JsonSerializer调用另一个序列化程序?

[英]How to invoke another serializer from a custom Gson JsonSerializer?

I have my custom class User : 我有自定义类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: 我现在正在为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;
}

But I already have a TimestampAdapter that I use for Timestamp.class . 但我已经有一个TimestampAdapter用于Timestamp.class How can I invoke this JsonSerializer to be used on the "created"-field in User.class ? 我怎样才能调用这个JsonSerializer要对在“创造” -场使用User.class

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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