使用 Play 框架,我通过 GSON 序列化我的模型。我指定哪些字段是公开的,哪些不公开。
这很好用,但我也想@expose 方法。当然,这也太简单了。
我该怎么做?
感谢您的帮助!
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() {
// ...
}
}
最佳答案
我遇到这个问题的最佳解决方案是制作一个专用的序列化器:
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;
}
}
并在我看来像这样使用它:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Account.class, new AccountSerializer());
Gson parser = gson.create();
renderJSON(parser.toJson(json));
但是让 @Expose
为方法工作会很棒:它可以避免仅仅为了显示方法而制作序列化程序!
关于java - 如何使用 GSon 公开方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416276/