Cyril N. Cyril N. - 1 year ago 163
Java Question

How to expose a method using GSon?

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 {
public String username;

public String email;

public String password;

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

Answer Source

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

public class AccountSerializer implements JsonSerializer<Account> {

    public JsonElement serialize(Account account, Type type, JsonSerializationContext context) {
        JsonObject root = new JsonObject();
        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();

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