Validator checks elements in Array/List. Validator allows Count == 0

This commit is contained in:
yutopp 2019-01-09 22:28:58 +09:00
parent cbd158c81d
commit 4d01aff7e3
2 changed files with 81 additions and 3 deletions

View File

@ -330,5 +330,55 @@ namespace UniJSON
Assert.True(c.IsEmpty());
}
class HasArrayOBject
{
[ItemJsonSchema(Minimum = 0.0, Maximum = 1.0)]
public float[] xs;
}
[Test]
public void HasArrayObjectValidator()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<HasArrayOBject>();
Assert.Null(s.Validator.Validate(c, new HasArrayOBject { xs = new float[] {} }));
Assert.Null(s.Validator.Validate(c, new HasArrayOBject { xs = new float[] { 0.5f } }));
Assert.NotNull(s.Validator.Validate(c, new HasArrayOBject { xs = new float[] { 1.5f } }));
Assert.True(c.IsEmpty());
}
}
class HasListObject
{
[ItemJsonSchema(Minimum = 0.0, Maximum = 1.0)]
public List<float> xs;
}
[Test]
public void HasListObjectValidator()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<HasListObject>();
Assert.Null(s.Validator.Validate(c, new HasListObject { xs = new List<float> {} }));
Assert.Null(s.Validator.Validate(c, new HasListObject { xs = new List<float> { 0.5f } }));
Assert.NotNull(s.Validator.Validate(c, new HasListObject { xs = new List<float> { 1.5f } }));
Assert.True(c.IsEmpty());
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
@ -145,10 +146,12 @@ namespace UniJSON
}
var count = GenericCounter<T>.Count(o);
if (count == 0)
// Empty array is valid
/*if (count == 0)
{
return new JsonSchemaValidationException(context, "empty");
}
}*/
if (MaxItems.HasValue && count > MaxItems.Value)
{
@ -160,6 +163,31 @@ namespace UniJSON
return new JsonSchemaValidationException(context, "minItems");
}
var v = Items.Validator;
var t = o.GetType();
IEnumerable iter = null;
if (t.IsArray)
{
iter = o as Array;
}
else if (t.GetIsGenericList())
{
iter = o as IList;
}
else
{
return new JsonSchemaValidationException(context, "non iterable object");
}
foreach(var e in iter)
{
var ex = v.Validate(context, e);
if (ex != null)
{
return ex;
}
};
return null;
}
@ -252,7 +280,7 @@ namespace UniJSON
}
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
src.Deserialize(ref dst);