If I have a JSON Schema that specifies a default value for a property, like
{
"type" : "object",
"properties" : {
"foo" : { "type" : "string" },
"bar" : { "type" : "string", "default" : "some text" }
}
}
...and a JSON string like
{
"foo" : "lorem ipsum"
}
...how can I deserialize that JSON string so that bar
is set to "some text" (the default value) instead of null?
JSON Schema validation does not modify the instance data. The default key word in JSON Schema is an annotation key word.
It sits under the Newtonsoft. Json. Schema namespace. JSON Schema is used to validate the structure and data types of a piece of JSON, similar to XML Schema for XML. You can read more about JSON Schema at json-schema.org.
JSON Schema is a grammar language for defining the structure, content, and (to some extent) semantics of JSON objects. It lets you specify metadata (data about data) about what an object's properties mean and what values are valid for those properties.
The primary strength of JSON Schema is that it generates clear, human- and machine-readable documentation. It's easy to accurately describe the structure of data in a way that developers can use for automated validation. This makes work easier for developers and testers, but the benefits go beyond productivity.
In json schemas, the "default" property is only a metadata (as "title" and "description" are) it is therefore not supposed to use it as a value fallback if none is provided (assuming you deserialize an object using a schema). This said, I personally made a deserializer using this default value as a fallback if we want to create an document instance from a schema. It is nevertheless not the general case.
I traced the references in the Json.NET source code, and the default attribute is apparently parsed, but not used for anything. So, the answer to my own question is: You can't use it in the current Json.NET version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With