How do you use the JSON Schema 'default' attribute in Json.NET?
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开发者_Go百科 string so that bar
is set to "some text" (the default value) instead of null?
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.
When porting object for many uses, validation, form rendering, documentation and testing it is the architect's decision on when and how to utilize defaults, and you will most likely make use of defaults. If you are looking for a prepackaged one size fits all solution that can handle the extra data storage and transfer costs of the duplicative defaults, then perhaps other schema methodologies have better .NET support (xml).
精彩评论