c# - 在 Newtonsoft JSON.NET 模式中禁用空类型

标签 c# .net json json.net jsonschema

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

public class Form
{
    [Required()]
    public string[] someStrings { get; set; }
}

这是由 Json.net 架构制作的架构:

"someStrings": {
  "type": "array",
  "items": {
    "type": [
      "string",
      "null"
    ]
  }
}

当我期待这个时:

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

请帮我去掉那个“null”。

最佳答案

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

关于c# - 在 Newtonsoft JSON.NET 模式中禁用空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43610133/

相关文章:

c# - 如何将浏览器重定向到 ASP.NET 中的本地文件?

c# - 计算大字符串的散列时如何避免分配大 Byte[]

.NET 用固定空格格式化字符串

json - 错误字符串的长度超过了maxJsonLength属性设置的值

jquery - 将数组的 JSON 数组转换为 <ul> 和 <li> 元素

c# - 使用 Bitmiracle Libtiff.net 创建 Bigtiff (>4GB) 文件

c# - 按日期值排序列表

c# - WPF Datagrid 未正确显示数据但在单击列标题时正确显示

.net - 在 Azure DevOps 持续部署期间无法获取资源类型 'Microsoft.Web/Sites' 和资源名称 'AppService' 的资源 ID

java - jackson 反序列化json到java对象