我不相信JSON Schema 标准支持“矩形阵列”约束,请参阅How to define a two-dimensional rectangular array in JSON Schema? 进行确认。 Json.NET 架构为二维数组生成一维数组架构这一事实似乎是一个纯粹的错误。
作为一种解决方法,您可以使用custom JSchemaGenerationProvider 为 N 维多维数组生成 N 维交错数组模式。这样的模式不会捕获所有行都具有相同长度的约束,但它至少会捕获正确的数组嵌套深度。
首先,定义如下JSchemaGenerationProvider:
public class MultidimensionalArraySchemaProvider : JSchemaGenerationProvider
{
public override JSchema GetSchema(JSchemaTypeGenerationContext context)
{
if (CanGenerateSchema(context))
{
// Create a jagged N-d array type.
var type = context.ObjectType.GetElementType().MakeArrayType();
for (int i = context.ObjectType.GetArrayRank(); i > 1; i--)
// Disallow null array items for outer arrays
// context.Generator.DefaultRequired controls whether null is allowed for innermost array items.
type = typeof(ArrayRow<>).MakeGenericType(type);
// Return a schema for the jagged N-d array type.
return context.Generator.Generate(type);
}
else
throw new NotImplementedException();
}
public override bool CanGenerateSchema(JSchemaTypeGenerationContext context) =>
context.ObjectType.IsArray && context.ObjectType.GetArrayRank() > 1;
}
[JsonArray(AllowNullItems = false)]
class ArrayRow<T> : List<T> { }
那么,如果你的班级看起来像:
public class MyClass
{
public int[,] MyProperty { get; set; }
public string[,,,] MyProperty4D { get; set; }
}
你可以这样做:
var generator = new JSchemaGenerator();
generator.GenerationProviders.Add(new MultidimensionalArraySchemaProvider());
var schema = generator.Generate(typeof(MyClass));
结果:
{
"type": "object",
"properties": {
"MyProperty": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "integer"
}
}
},
"MyProperty4D": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": [
"string",
"null"
]
}
}
}
}
}
},
"required": [
"MyProperty",
"MyProperty4D"
]
}
演示小提琴here.
相关问题: