Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling null type in Newtonsoft JSON.NET schema

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.

like image 967
actorapz Avatar asked Apr 25 '17 12:04

actorapz


People also ask

How do I allow null values in JSON?

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.

What does NullValueHandling ignore do?

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.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Newtonsoft JSON 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.


1 Answers

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"
      }
    }
  }
}
like image 106
Randi Ratnayake Avatar answered Sep 18 '22 00:09

Randi Ratnayake