Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose a method using GSon?

Tags:

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() {         // ...     } } 
like image 253
Cyril N. Avatar asked Sep 14 '11 12:09

Cyril N.


People also ask

What is the use of @expose in Gson?

@SerializeName is used to set the key that json object will include ,however @Expose is used to decide whether the variable will be exposed for Serialisation and Deserialisation ,or not.

Which Gson methods are useful for implementing JSON?

Parsing JSON Into Java Objects GSON can pase JSON into Java objects using the fromJson() method of the Gson object. Here is an GSON example of parsing JSON into a Java object: String json = "{\"brand\":\"Jeep\", \"doors\": 3}"; Gson gson = new Gson(); Car car = gson.

How does Gson serialize?

Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.


1 Answers

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!

like image 193
Cyril N. Avatar answered Nov 29 '22 10:11

Cyril N.