On Fri, Sep 25, 2020 at 9:35 AM 'Christian' via jackson-user <jackson-user@googlegroups.com> wrote: > > Dear Jackson community, > > we are trying to enhance the Jackson serializer in one of our project. We > want to hide / ignore certain fields from certain objects conditionally. > Means certain fields should only be serialized to JSON when a specific > condition is true. We want to restrict certain fields based on the current > user access. > > Our idea is to pass a auth context to Jackson, this auth context will contain > information which fields the current user can see and which not. > > The difficult part now comes how we can hide certain fields based on this. > > What we already considered: > > JsonIgnore annotation (does not work, its static and not based on conditions) > JsonInclude annotation (does not work, its static and not based on conditions) > JsonView (not very practical, we would need to create one view class for each > field in all objects) > Using custom serializer as described here > https://www.baeldung.com/jackson-serialize-field-custom-criteria#2-custom-serializer > (Can only work to hide a complete object, not just certain fields) > > Does anyone has a good approach in Jackson to exclude / hide / ignore certain > fields dynamically?
Aside from these approaches, there are couple more, included here: http://www.cowtowncoder.com/blog/archives/2011/02/entry_443.html and probably most specifically use of "JsonFilter": http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html which is more dynamic but less manual than custom serializer. Aside from this a different approach would be to use two-phase approach where: 1. POJO is converted into JsonNode (JsonNode n = mapper.valueToTree(pojo);) first, and 2. Filtering logic is implemented on JsonNode (remove entries based on whatever criteria; or change/rename; add) and then the resulting JsonNode is serialized. I think this is a quite widely used technique especially when step (2) is based on a list of fields to include passed from external sources (like as request parameter). I hope this helps, -+ Tatu +- -- You received this message because you are subscribed to the Google Groups "jackson-user" group. To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/jackson-user/CAL4a10hZ4B-Y_WFk5w5JiDMneo1a0sYwSYtVHpgtZHVogVBCrg%40mail.gmail.com.