2

I'm developing a CRUD web application which exposes a REST endpoint to update an existing document in a MongoDB collection.

The json object sent by the frontend only contains the fields that have to change.

Since the json parser will initialize all fields that were non present in the json object to null, how can I know if a field is null because the user wanted to remove that value, or because it doesn't have to be updated ?

The answer is probably that there is no way to know, but then my question rather is: how do people usually handle that case ?

Sending the full object each time and replacing it entirely in the DB is not an option for me, for several reasons (good practices, performance and also the way the frontend works).

I thought of a solution that could work but I'm not really happy with it:

  1. add an extra boolean flag for each field that is not mandatory (for the mandatory ones, I know I can't delete the value)
  2. intercept the json in a MessageBodyReader and parse the json myself
  3. if a field is present with null in the json, set the extra flag to true to mark it as "to delete"

This is the "cleanest" solution I could think of so far, but it requires so much extra work that I hope I can find another way.

Thanks in advance for any advise.

Fab
  • 135
  • 9
  • You can figure out the updated fields from incoming json object before you map them to your entities if it will only contains the changed field. Then you can map it to your entity. – cool Jul 27 '20 at 10:27
  • Thanks for explaining your problem _really well_ (i mean that)! When you say _"the json parser"_ - what do you mean, exactly? Which one do you use? Because the cleanest solution would be to find a nice flag/annotation that makes your parser behave as intended. – bkis Jul 27 '20 at 10:30
  • Hi, I'm using the "new" json-b spec and the implementation is yasson (but I always prefer to avoid using implementation specific features). I'm open to switch to jackson instead if it solves my issue but I'd rather stick with json-b if possible, as it's now the standard. I also thought of parsing the json null values to an empty string (or to send empty strings directly) to be able to make the distinction but that would not work for boolean or numbers. – Fab Jul 27 '20 at 11:12
  • I should also mention that I checked the json-b documentation and it seems that you can only modify the way null values are parsed TO json, and not FROM json. – Fab Jul 27 '20 at 11:19

0 Answers0