为什么我的数组对象在生成 JsonSchema 时是 "type": ["object","null"] 类型
Why are my array objects are of type "type": ["object","null"] when generating a JsonSchema
所以,我有一个 class 定义为...
public class foo
{
public List<bar> Bars {get;set;}
}
public class bar
{
public string foorbar {get;set;}
}
当我使用 JsonSchemaGenerator
生成其模式时,我得到以下输出...
var generator = new JsonSchemaGenerator();
return generator.Generate(typeof(foo), false);
{
"type": "object",
"properties" : {
"Bars":{
"type": "array",
"items": {
"type": ["object","null"],
"properties": {
"foorbar":{"type":"string"}
}
}
}
}
}
那么,为什么我的项目在 "type": ["object","null"]
类型的数组中
我认为这是导致问题的原因,我如何才能在此处删除可为 null 的对象类型?
谢谢
方案允许 null
因为你可以做这样的事情并尝试序列化它,这在 C# 端是完全有效的:
myFoo.Bars.Add(null);
要禁止数组 JSON 侧的 null
值,您需要使用 JsonArrayAttribute
。不幸的是,这个属性不能添加到字段中;它需要添加到 class。这意味着您需要创建一个 class 来包装 List<bar>
并将属性应用于它。最终的 class 结构如下所示:
public class foo
{
public ListOfBar Bars { get; set; }
}
public class bar
{
public string foorbar { get; set; }
}
[JsonArray(false)]
public class ListOfBar : List<bar> {}
可以找到有关属性的详细信息 here。
通过查看 JsonSchemaGenerator
的 source code,特别是第 285 行,我找到了这个属性。
所以,我有一个 class 定义为...
public class foo
{
public List<bar> Bars {get;set;}
}
public class bar
{
public string foorbar {get;set;}
}
当我使用 JsonSchemaGenerator
生成其模式时,我得到以下输出...
var generator = new JsonSchemaGenerator();
return generator.Generate(typeof(foo), false);
{
"type": "object",
"properties" : {
"Bars":{
"type": "array",
"items": {
"type": ["object","null"],
"properties": {
"foorbar":{"type":"string"}
}
}
}
}
}
那么,为什么我的项目在 "type": ["object","null"]
我认为这是导致问题的原因,我如何才能在此处删除可为 null 的对象类型?
谢谢
方案允许 null
因为你可以做这样的事情并尝试序列化它,这在 C# 端是完全有效的:
myFoo.Bars.Add(null);
要禁止数组 JSON 侧的 null
值,您需要使用 JsonArrayAttribute
。不幸的是,这个属性不能添加到字段中;它需要添加到 class。这意味着您需要创建一个 class 来包装 List<bar>
并将属性应用于它。最终的 class 结构如下所示:
public class foo
{
public ListOfBar Bars { get; set; }
}
public class bar
{
public string foorbar { get; set; }
}
[JsonArray(false)]
public class ListOfBar : List<bar> {}
可以找到有关属性的详细信息 here。
通过查看 JsonSchemaGenerator
的 source code,特别是第 285 行,我找到了这个属性。