gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:31 25 4
gpt4 key购买 nike

我正在使用 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 设置来展平继承层次...

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

关于c# - 如何确保 NJsonSchema 只包含必填字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com