How do you use the JSON Schema 'default' attribute in Json.NET?

Batibix picture Batibix · Aug 10, 2011 · Viewed 17.1k times · Source

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?

Answer

Flavien Volken picture Flavien Volken · Jul 20, 2012

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.