简体   繁体   中英

Exclude datamember when using renderJSON with play framework

I need to render objects in JSON and send them to the client but I need to exclude fields like email and password for obvious reasons.

I know play uses GSON (by google?) and you can pass a serializer class when calling the renderJSON() method. However I'm rendering different types of classes at once using a container class:

public class JSONContainer {

    public List<User> userList;

    public List<Toy> toyList;

}

For each class it's possible to make a Serializer class implementing GSON's JsonSerializer<...> method. But if I render a JSONContainer object like this: renderJSON(container) how can I pass the serializer classes to the rendering method?

Or is there maybe an easier/better way to do this?

Take a look at this post , which gives you a couple of options.

It would appear that the best option is to the @Expose ( com.google.gson.annotations.Expose ) annotation to mark the fields that you want to be serialised by Gson. You then need to use the GsonBuilder to specifically only include the @Expose fields.

Alternatively, as you have mentioned in your post, you can simply build your serialisations yourself. If you look at this post , it shows how specific class types are registered against the GsonBuilder, so any object of that found as part of the serialisation will use your specific serialiser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM