Skip Properties When Deserializing POJOs

A commonly requested feature in Jackson is the ability to “skip” certain properties during deserialization, but include them during serialization. This might be desirable in the case of a computed property.

It might also be desirable if certain properties should never be read from a user request for security or other reasons, but may need to be returned to the user as part of a response. This could be true for several field types such as a user ID, an API key, or, as previously mentioned, a computed field.

Since it appears that the feature won’t be making it into the library anytime soon, I found a reasonably clean way of doing it. There may be other ways to achieve this behavior, mind you, I have only recently begun using Jackson (and Java, really, at least for significant projects) so I’m definitely no expert.

https://gist.github.com/glesica/dc5a1e2059fe5fa9a0b2

The RequestJson class may then be used for deserialization without worry and the ResponseJson class may be used to return the extra properties to the user. In some sense, this is the whole point of inheritance. Requests do not include certain properties (like a user ID), but responses do, in addition to the request properties. I was a bit surprised that in several minutes of Googling, I didn’t see this solution suggested.

Advertisements