Question

I have a Json model that requires at least one field out of two be set. Put another way, it should not allow for all null fields, and at the same time should not require that both fields are specified.

Is there a way to accomplish this with Jackson?

Was it helpful?

Solution

The crucial decision to make is whether the constraint that you describe is a system/technical one, or one specified by the business logic of your application. Jackson is merely a serialization/deserialization library. Verifying the semantic correctness of the serialized data is generally beyond its scope.

You can, of course, use a custom deserializer that will verify the correctness of the input and throw a JsonParseException on invalid input. This approach, however, might leave the parser in an unstable state. Therefore it should be used to catch issues related to the serialization itself, such as trying to deserialize an incompatible version of an object, where discarding the whole input is often a valid solution.

For most cases, I would suggest leaving any in-depth validation of user input to your actual application code. Keep the serializer and deserializer implementations as simple as possible - that will let them remain unchanged even when the application logic changes.

Trying to incorporate actual business logic into the JSON parser would only complicate your architecture. It would mix the handling of system errors, such as the serialization of incompatible objects, with application errors, such as a malicious client filling in fields related to distinct user groups at the same time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top