Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
John Reynolds Avatar asked Aug 10 '11 13:08

John Reynolds


People also ask

What is default JSON Schema?

JSON Schema validation does not modify the instance data. The default key word in JSON Schema is an annotation key word.

What is JSON net schema?

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.

How does JSON Schema work?

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.

Why do we use JSON Schema?

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.


2 Answers

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.

like image 176
Flavien Volken Avatar answered Oct 13 '22 15:10

Flavien Volken


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.

like image 20
John Reynolds Avatar answered Oct 13 '22 13:10

John Reynolds