如何使用GSon公开一个方法? [英] How to expose a method using GSon?

查看:84
本文介绍了如何使用GSon公开一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Play Framework,我通过GSON序列化我的模型。我指定哪些字段是暴露的,哪些不是。



这很好用,但我也想用@expose方法。当然,这太简单了。



我该怎么做?

感谢您的帮助! / p>

  public class Account extends Model {
@Expose
public String username;

@Expose
public String email;

公共字符串密码;

@Expose //当然,这不起作用
public String getEncodedPassword(){
// ...
}
}


解决方案

我遇到这个问题的最佳解决方案是制作一个专用序列化程序:

  public class AccountSerializer实现JsonSerializer< Account> {

@Override
public JsonElement serialize(Account account,Type type,JsonSerializationContext context){
JsonObject root = new JsonObject();
root.addProperty(id,account.id);
root.addProperty(email,account.email);
root.addProperty(encodedPassword,account.getEncodedPassword());

返回root;
}

}

并且像这样使用它我的看法:

pre $ g $ c $ gsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Account.class,new AccountSerializer());
Gson parser = gson.create();
renderJSON(parser.toJson(json));

但是,有一个方法可以使用 @Expose 会很好:它会避免仅仅为了显示方法而使用序列化程序!


Using Play Framework, I serialize my models via GSON. I specify which fields are exposed and which aren't.

This works great but I'd also like to @expose method too. Of course, this is too simple.

How can I do it ?

Thanks for your help !

public class Account extends Model {
    @Expose
    public String username;

    @Expose
    public String email;

    public String password;

    @Expose // Of course, this don't work
    public String getEncodedPassword() {
        // ...
    }
}

解决方案

The best solution I came with this problem was to make a dedicated serializer :

public class AccountSerializer implements JsonSerializer<Account> {

    @Override
    public JsonElement serialize(Account account, Type type, JsonSerializationContext context) {
        JsonObject root = new JsonObject();
        root.addProperty("id", account.id);
        root.addProperty("email", account.email);
        root.addProperty("encodedPassword", account.getEncodedPassword());

        return root;
    }

}

And to use it like this in my view:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Account.class, new AccountSerializer());
Gson parser = gson.create();
renderJSON(parser.toJson(json));

But having @Expose working for a method would be great: it would avoid making a serializer just for showing methods!

这篇关于如何使用GSon公开一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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