如何从定制的Gson JsonSerializer调用另一个序列化程序? [英] How to invoke another serializer from a custom Gson JsonSerializer?

查看:293
本文介绍了如何从定制的Gson JsonSerializer调用另一个序列化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的自定义类用户

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

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

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

但是我已经有了一个 TimestampAdapter 用于 Timestamp.class 。我如何调用这个 JsonSerializer 来在 User.class

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

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.

这篇关于如何从定制的Gson JsonSerializer调用另一个序列化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆