John Reynolds
John Reynolds

Reputation: 5057

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 string so that bar is set to "some text" (the default value) instead of null?

Upvotes: 20

Views: 20348

Answers (3)

user3483339
user3483339

Reputation: 29

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).

Upvotes: -1

Flavien Volken
Flavien Volken

Reputation: 21339

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.

Upvotes: 18

John Reynolds
John Reynolds

Reputation: 5057

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.

Upvotes: 9

Related Questions