C# 在Newtonsoft JSON.NET架构中禁用空类型

C# 在Newtonsoft JSON.NET架构中禁用空类型,c#,.net,json,json.net,jsonschema,C#,.net,Json,Json.net,Jsonschema,我有一个MVC应用程序,它将我的模型序列化为json模式(使用Newtonsoft json.net模式)。问题是数组中的项具有类型[“string”,“null”],但我需要的只是“string”。以下是我的课程代码: public class Form { [Required()] public string[] someStrings { get; set; } } 这是由Json.net模式生成的模式: "someStrings": { "type": "array

我有一个MVC应用程序,它将我的模型序列化为json模式(使用Newtonsoft json.net模式)。问题是数组中的项具有类型
[“string”,“null”]
,但我需要的只是
“string”
。以下是我的课程代码:

public class Form
{
    [Required()]
    public string[] someStrings { get; set; }
}
这是由Json.net模式生成的模式:

"someStrings": {
  "type": "array",
  "items": {
    "type": [
      "string",
      "null"
    ]
  }
}
在我期待的时候:

"someStrings": {
  "type": "array",
  "items": {
    "type": "string"        
  }
}

请帮我清除该“空值”。

生成架构时,请尝试将
DefaultRequired
设置为
DisallowNull

JSchemaGenerator generator = new JSchemaGenerator() 
{ 
    DefaultRequired = Required.DisallowNull 
};

JSchema schema = generator.Generate(typeof(Form));
schema.ToString();
输出:

{
  "type": "object",
  "properties": {
    "someStrings": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  }
}
您可以尝试以下方法:

   [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
试试这个:

     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);
输出:带null
输出:不带null
没有变化:(你自己做序列化吗?如果是,你可以试试这个:我想我不应该使用术语“序列化”在我的问题中,因为我所做的只是通过类生成模式。所以答案是否定的,我没有进行序列化。请注意,此解决方案需要Newtonsoft.JsonSchema包-该类在Newtonsoft.Json包中不可用。
// {
//   "Name": "Heisenberg",
//   "Age": 44,
//   "Salary": null
// }
 string jsonWithOutNullValues = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });
// {
//   "Name": "Heisenberg",
//   "Age": 44
// }