如何使用GSon公开方法?
问题内容:
使用Play Framework,我通过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
为某个方法工作会很棒:它将避免使序列化器仅用于显示方法!