✅ Json Validation and Populating with Nulls if Missing
Hi I am trying to validate an input json against a C# object model. There are instances where sometimes nested properties are not a part of this input json and I'd been asked to ensure the json has the correct structure and populate missing props with nulls as values. Anyone encounter something like this before?
10 Replies
Make your models props nullable where they are optional.
Deserialize to the model. Non-existing props will be given null values.
Serialize the model instance, but with the "write nulls" option turned on.
Shouldnt that solve your issues?
The effort here is mainly to homogenize input jsons ahead of deserialization as it seems like this could be a simple (but maybe not)
and these "jsons" are... strings? currently?
it seems kinda backwards to spend quite a bit of effort to analyze and homogenize your strings before deserializing, if the only goal with doing that is setting a bunch of properties to null. Let the deserializer handle that instead by correctly modelling your data with nullability indicators - its then automatic as part of deserialization
Yes and that is true if it is indeed quite a bit of effort which is what I am starting to see (deep nesting and arrays)
you'd essentially have to build a json parser, and somehow teach it the shape of your models
I hoping to just create a newtonsoft JObject from the json string file and compare against a defined JSchema (currently generated) with conditions to infill missing objects or properties with nulls. But configuring this is a bit challenging with deeper nesting
this is what I'd do
we can see that height and the cars are nullable, and the json contains no height. it gets the value
null
after deserializationRight that is the forward process but I am exploring this backwards thing with a json schema
I really can't see why or to what ends, but you do you 🙂
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View