Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

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

    @Expose
    public String email;

    public String password;

    @Expose // Of course, this don't work
    public String getEncodedPassword() {
        // ...
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...