I have a WebApi written in C#. In this WebApi I turn the JSON I receive into classes. Let's C1 be one of these classes. C1 contains the property P1 and P2 and P3 respectively of types T1 and T2 and T3.
The client has to send a PUT request which builds a JSON carrying this information:
- Change value of P1 to another one but not null
- Do nothing to P2 (keep the current value)
- Set P3 to null
C# classes can not make the difference between the second and third cases since there is no such thing as 'undefined' state for variables hence my problem to serialize my JSON into C1 without loosing this information.
Most serializers I know will act accordingly with this strategy:
A null, absent or undefined value in the JSON will result into a null value in the corresponding class's property.
These are my solutions:
- I can define a new Type which encompasses the real Type T1 and holds this information with members
Optional#IsDefined
to determine whether it's defined or not andOptions#Value
to retrieve the actual value when it's defined. When I receive a JSON I follow this strategy:
If the JSON property is set to undefined or is absent then I set the corresponding C1's property to
Optional<T1>.absent()
, if the JSON property is equal to null I set C1's property to null.
- I can decide that some values will mean that the value undefined. For example if T1 is an Integer I state that the maximum value means this value is undefined. Doing this requires a JSON holding specific values when I want those values to be ignored by the server. For instance if I want an integer value to be ignored I have to set it the the maximum integer value possible. With this option I have to follow the following strategy:
If the JSON property is set to a specific value I decided would mean undefined I set the property to what it already is in my database. If the property is null I set the class's property to null.
Questions
What is the best strategy to avoid such a loss of information?
Which option is better (knowing that the first one implies a re-factoring cost to my team)?
Are there any better options than those I exposed?