How to invoke another serializer from a custom Gson JsonSerializer?

为君一笑 提交于 2019-12-21 07:18:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!