Skip to main content
 首页 » 编程设计

c#之如何确保 NJsonSchema 只包含必填字段

2024年02月05日7soundcode

我正在使用 NJsonSchema v2.6 用于为以下类生成 JSON 模式:

[DataContract(Name = "Message", Namespace = "")] 
public class AMessageModel 
{ 
    [DataMember] 
    internal Guid MessageId { get; set; } 
 
    internal DateTime MessageDate { get; set; } 
} 
 
[DataContract(Name = "Message", Namespace = "")] 
public class AddUserMessage : AMessageModel 
{ 
    [DataMember] 
    public string AccountName { get; set; } 
 
    [DataMember] 
    public string FistName { get; set; } 
 
    [Range(2, 5)] 
    [DataMember] 
    public string LastName { get; set; } 
 
    [DataMember] 
    public string Email { get; set; } 
 
    [DataMember] 
    public string Password { get; set; } 
} 

生成的 JSON 模式:

        { 
          "$schema": "http://json-schema.org/draft-04/schema#", 
          "type": "object", 
          "typeName": "AddFitnessHubAccountMessage", 
          "additionalProperties": false, 
          "properties": { 
            "AccountName": { 
              "type": [ 
                "null", 
                "string" 
              ] 
            }, 
            "FistName": { 
              "type": [ 
                "null", 
                "string" 
              ] 
            }, 
            "LastName": { 
              "type": [ 
                "null", 
                "string" 
              ] 
            }, 
            "Email": { 
              "type": [ 
                "null", 
                "string" 
              ] 
            }, 
            "Password": { 
              "type": [ 
                "null", 
                "string" 
              ] 
            } 
          }, 
          "allOf": [ 
            { 
              "type": "object", 
              "typeName": "AMessageModel", 
              "additionalProperties": false, 
              "properties": { 
                "MessageId": { 
                  "type": "string", 
                  "format": "guid" 
                }, 
                "MessageDate": { 
                  "type": "string", 
                  "format": "date-time" 
                } 
              } 
            } 
          ] 
        } 

即使 MessageDate 属性未标记为 DataMember,它始终包含在模式中,而且生成的模式包含两个模式路径,而它应该只包含一个,似乎解析器没有展平属性。

更新

这解决了创建多个模式路径的问题

new JsonSchemaGeneratorSettings 
{ 
    FlattenInheritanceHierarchy = true 
} 

GitHub 问题:https://github.com/NJsonSchema/NJsonSchema/issues/53

请您参考如下方法:

我是图书馆的作者 NJsonSchema .

忽略的属性

库中有一个错误,现在 (v2.7+) 属性忽略的工作方式如下:

A property is ignored when either

  1. The property is marked with the JsonIgnoreAttribute property
  2. The class has an DataContractAttribute attribute and the property has no DataMemberAttribute and no JsonPropertyAttribute

https://github.com/NJsonSchema/NJsonSchema/wiki/JsonSchemaGenerator

扁平化继承层次结构

正如您已经发现的,您可以通过 FlattenInheritanceHierarchy 设置来展平继承层次...

库主要用于代码生成,因此通常需要继承。