5
votes

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.

3

3 Answers

6
votes

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"
      }
    }
  }
}
0
votes

You can try this:

   [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
-1
votes

Try this ::

     public class Employee 
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public decimal? Salary { get; set; }
        }    

        Employee employee= new Employee
            {
                Name = "Heisenberg",
                Age = 44
            };

            string jsonWithNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);

output: with null

// {
//   "Name": "Heisenberg",
//   "Age": 44,
//   "Salary": null
// }

 string jsonWithOutNullValues = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

output: without null

// {
//   "Name": "Heisenberg",
//   "Age": 44
// }