I have an MVC application, that serializes my model into json schema (using Newtonsoft json.net schema). The problem is that items in my array have type ["string", "null"]
, but what I need is just "string"
. Here is code for my class:
public class Form
{
[Required()]
public string[] someStrings { get; set; }
}
This is schema made by Json.net schema:
"someStrings": {
"type": "array",
"items": {
"type": [
"string",
"null"
]
}
}
While I am expecting this:
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
Help me get rid of that "null" please.
To include null values in the JSON output of the FOR JSON clause, specify the INCLUDE_NULL_VALUES option. If you don't specify the INCLUDE_NULL_VALUES option, the JSON output doesn't include properties for values that are null in the query results.
This sample serializes an object to JSON with NullValueHandling set to Ignore so that properties with a default value aren't included in the JSON result.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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.
Try setting DefaultRequired
to DisallowNull
when you generate the schema:
JSchemaGenerator generator = new JSchemaGenerator()
{
DefaultRequired = Required.DisallowNull
};
JSchema schema = generator.Generate(typeof(Form));
schema.ToString();
Output:
{
"type": "object",
"properties": {
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
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