I’d like to know if a certain property in json was skipped or was provided null. For this I’m using a setter flag like this. This works fine but its much uglier and I will have to create flags for every property I want to check. Is there a neater solution, create a custom class that has functions like isSet, Value?
public class Tmp2
{
private int a;
public bool isASet;
private int? b;
public bool isBSet;
public int A { get { return a; }
set { a = value; isASet = true; } }
public int? B { get { return b; }
set { b = value; isBSet = true; } }
}
Looking for a better solution
2
Answers
this works for me
tests
test results
You could adopt the
Optional<T>
pattern from the question Custom JSON serializer for optional property with System.Text.Json by Maxime Rossini to wrap your values in anOptional<T>
struct that tracks whether or not the value was ever initialized. Since you are using Json.NET you will need to port its logic from System.Text.Json.First, define the following interface, struct and converter:
Now modify your classes (here
Tmp2
) and replace the value of every property whose presence you want to track with anOptional<T>
wrapper like so:And now you will be able to tell whether any particular value was ever set by checking
value.HasValue
, e.g.:In order to suppress output of unset properties when serialized, you have two options:
Mark each property with `[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] :
Introduce a custom contract resolver that automatically suppresses serialization of unset property values.
The version of
Tmp2
above uses approach #1 but if you prefer #2, define the following contract resolver:And simplify your model as follows:
And you will now be able to round-trip
Tmp2
and track the presence of properties using the following settings:Demo fiddle here.