【问题标题】:Disabling null type in Newtonsoft JSON.NET schema在 Newtonsoft JSON.NET 架构中禁用空类型
【发布时间】:2017-09-22 10:28:06
【问题描述】:

我有一个 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"        
  }
}

请帮我摆脱那个“空”。

【问题讨论】:

    标签: c# .net json json.net jsonschema


    【解决方案1】:

    试试这个 ::

         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);
    

    输出:带空

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

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

    输出:无空

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 注意这个解决方案需要 Newtonsoft.JsonSchema 包 - 这个类在 Newtonsoft.Json 包中不可用。
      【解决方案3】:

      你可以试试这个:

         [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
      

      【讨论】:

      • 没有变化:(
      • 你自己做序列化吗?如果是,你可以试试这个:newtonsoft.com/json/help/html/NullValueHandlingIgnore.htm
      • 我想我不应该在我的问题中使用术语“序列化”,因为我所做的只是由我的班级生成模式。所以答案是否定的,我不做序列化。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多