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() { // ... } }
@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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With