在Newtonsoft JSON.NET架构中禁用null类型

时间:2017-04-25 12:02:29

标签: 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",
  "items": {
    "type": [
      "string",
      "null"
    ]
  }
}

虽然我期待这个:

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

请帮我摆脱那个“空”。

3 个答案:

答案 0 :(得分:4)

在生成架构时尝试将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"
      }
    }
  }
}

答案 1 :(得分:0)

你可以试试这个:

   [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

答案 2 :(得分:0)

尝试一下::

     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

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

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

输出:不包含空值

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