-Lots and lots of JSON Schema work

-JSON Schema spec tests added
-Added Path to JToken
-Fixed JTokenWriter returning null reference
-Build script logging
-Documentation
-Updated to NUnit 2.6
This commit is contained in:
James Newton-King
2012-12-31 00:53:08 +13:00
parent 86a9b7b66b
commit e3a720504e
110 changed files with 19585 additions and 5992 deletions
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -1068,12 +1068,12 @@ namespace Newtonsoft.Json.Tests
}
[Test]
public void NoAdditionalProperties()
public void NoAdditionalItems()
{
string schemaJson = @"{
""type"":""array"",
""items"": [{""type"":""string""},{""type"":""integer""}],
""additionalProperties"": false
""additionalItems"": false
}";
string json = @"[1, 'a', null]";
@@ -75,6 +75,23 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(ReferenceEquals(newValue1, newValue2));
}
[Test]
public void JObjectCount()
{
JObject o = new JObject();
dynamic d = o;
long? c1 = d.Count;
o["Count"] = 99;
long? c2 = d.Count;
Assert.AreEqual(null, c1);
Assert.AreEqual(99, c2);
}
[Test]
public void JObjectEnumerator()
{
@@ -949,5 +949,38 @@ namespace Newtonsoft.Json.Tests.Linq
JToken.Parse(json);
});
}
[Test]
public void Path()
{
JObject o =
new JObject(
new JProperty("Test1", new JArray(1, 2, 3)),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))),
new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3)))
);
JToken t = o.SelectToken("Test1[0]");
Assert.AreEqual("Test1[0]", t.Path);
t = o.SelectToken("Test2");
Assert.AreEqual("Test2", t.Path);
t = o.SelectToken("");
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test4[0][0]");
Assert.AreEqual("Test4[0][0]", t.Path);
t = o.SelectToken("Test4[0]");
Assert.AreEqual("Test4[0]", t.Path);
t = t.DeepClone();
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test3.Test1[1].Test1");
Assert.AreEqual("Test3.Test1[1].Test1", t.Path);
}
}
}
@@ -25,6 +25,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
#if !NETFX_CORE
using NUnit.Framework;
@@ -362,6 +363,39 @@ namespace Newtonsoft.Json.Tests.Linq
var o = JObject.Parse(json);
o.Property("DateTimeOffset").Value = dateTimeOffset;
}
public void ParseAndConvertDateTimeOffset()
{
var json = @"{ d: ""\/Date(0+0100)\/"" }";
using (var stringReader = new StringReader(json))
using (var jsonReader = new JsonTextReader(stringReader))
{
jsonReader.DateParseHandling = DateParseHandling.DateTimeOffset;
var obj = JObject.Load(jsonReader);
var d = (JValue)obj["d"];
Assert.IsInstanceOfType(typeof(DateTimeOffset), d.Value);
TimeSpan offset = ((DateTimeOffset)d.Value).Offset;
Assert.AreEqual(TimeSpan.FromHours(1), offset);
DateTimeOffset dateTimeOffset = (DateTimeOffset) d;
Assert.AreEqual(TimeSpan.FromHours(1), dateTimeOffset.Offset);
}
}
public void ReadDatesAsDateTimeOffsetViaJsonConvert()
{
var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
var jsonSerializerSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind };
JObject obj = (JObject)JsonConvert.DeserializeObject(content, jsonSerializerSettings);
object startDateTime = obj["startDateTime"];
Assert.IsInstanceOfType(typeof(DateTimeOffset), startDateTime);
}
#endif
}
}
@@ -864,5 +864,24 @@ keyword such as type of business.""
JArray a = JArray.Parse(json);
Assert.AreEqual("hi!", (string)a[0]);
}
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
[Test]
public void ExceptionFromOverloadWithJValue()
{
dynamic name = new JValue("Matthew Doig");
IDictionary<string, string> users = new Dictionary<string, string>();
// unfortunatly there doesn't appear to be a way around this
ExceptionAssert.Throws<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>("The best overloaded method match for 'System.Collections.Generic.IDictionary<string,string>.Add(string, string)' has some invalid arguments",
() =>
{
users.Add("name2", name);
Assert.AreEqual(users["name2"], "Matthew Doig");
});
}
#endif
}
}
@@ -149,6 +149,7 @@
<Compile Include="Linq\DynamicTests.cs" />
<Compile Include="Linq\JPathTests.cs" />
<Compile Include="Linq\JRawTests.cs" />
<Compile Include="Schema\JsonSchemaSpecTests.cs" />
<Compile Include="Serialization\ConstructorHandlingTests.cs" />
<Compile Include="Serialization\ContractResolverTests.cs" />
<Compile Include="Serialization\DefaultValueHandlingTests.cs" />
@@ -309,6 +310,69 @@
<LastGenOutput>LinqToSqlClasses.designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</None>
<None Include="Schema\Specs\additionalItems.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\additionalProperties.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\dependencies.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\disallow.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\divisibleBy.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\enum.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\extends.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\items.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\maximum.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\maxItems.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\maxLength.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\minimum.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\minItems.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\minLength.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\pattern.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\patternProperties.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\properties.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\ref.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\required.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\type.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Schema\Specs\uniqueItems.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{3259AA49-8AA1-44D3-9025-A0B520596A8C}" />
@@ -347,6 +411,9 @@
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Folder Include="Schema\Specs\optional\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -76,5 +76,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.11.15520")]
[assembly: AssemblyFileVersion("4.5.11.15631")]
#endif
@@ -300,14 +300,156 @@ namespace Newtonsoft.Json.Tests.Schema
public void DivisibleBy_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 is not evenly divisible by 3.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.DivisibleBy = 3;
() =>
{
JsonSchema schema = new JsonSchema();
schema.DivisibleBy = 3;
JValue v = new JValue(10);
v.Validate(schema);
});
JValue v = new JValue(10);
v.Validate(schema);
});
}
[Test]
public void UniqueItems_SimpleUnique()
{
JsonSchema schema = new JsonSchema();
schema.UniqueItems = true;
JArray a = new JArray(1, 2, 3);
Assert.IsTrue(a.IsValid(schema));
}
[Test]
public void UniqueItems_SimpleDuplicate()
{
JsonSchema schema = new JsonSchema();
schema.UniqueItems = true;
JArray a = new JArray(1, 2, 3, 2, 2);
IList<string> errorMessages;
Assert.IsFalse(a.IsValid(schema, out errorMessages));
Assert.AreEqual(2, errorMessages.Count);
Assert.AreEqual("Non-unique array item at index 3.", errorMessages[0]);
Assert.AreEqual("Non-unique array item at index 4.", errorMessages[1]);
}
[Test]
public void UniqueItems_ComplexDuplicate()
{
JsonSchema schema = new JsonSchema();
schema.UniqueItems = true;
JArray a = new JArray(1, new JObject(new JProperty("value", "value!")), 3, 2, new JObject(new JProperty("value", "value!")), 4, 2, new JObject(new JProperty("value", "value!")));
IList<string> errorMessages;
Assert.IsFalse(a.IsValid(schema, out errorMessages));
Assert.AreEqual(3, errorMessages.Count);
Assert.AreEqual("Non-unique array item at index 4.", errorMessages[0]);
Assert.AreEqual("Non-unique array item at index 6.", errorMessages[1]);
Assert.AreEqual("Non-unique array item at index 7.", errorMessages[2]);
}
[Test]
public void UniqueItems_NestedDuplicate()
{
JsonSchema schema = new JsonSchema();
schema.UniqueItems = true;
schema.Items = new List<JsonSchema>
{
new JsonSchema
{
UniqueItems = true
}
};
schema.PositionalItemsValidation = false;
JArray a = new JArray(
new JArray(1, 2),
new JArray(1, 1),
new JArray(3, 4),
new JArray(1, 2),
new JArray(1, 1)
);
IList<string> errorMessages;
Assert.IsFalse(a.IsValid(schema, out errorMessages));
Assert.AreEqual(4, errorMessages.Count);
Assert.AreEqual("Non-unique array item at index 1.", errorMessages[0]);
Assert.AreEqual("Non-unique array item at index 3.", errorMessages[1]);
Assert.AreEqual("Non-unique array item at index 1.", errorMessages[2]);
Assert.AreEqual("Non-unique array item at index 4.", errorMessages[3]);
}
[Test]
public void Enum_Properties()
{
JsonSchema schema = new JsonSchema();
schema.Properties = new Dictionary<string, JsonSchema>
{
{
"bar",
new JsonSchema
{
Enum = new List<JToken>
{
new JValue(1),
new JValue(2)
}
}
}
};
JObject o = new JObject(
new JProperty("bar", 1)
);
IList<string> errorMessages;
Assert.IsTrue(o.IsValid(schema, out errorMessages));
Assert.AreEqual(0, errorMessages.Count);
o = new JObject(
new JProperty("bar", 3)
);
Assert.IsFalse(o.IsValid(schema, out errorMessages));
Assert.AreEqual(1, errorMessages.Count);
}
[Test]
public void UniqueItems_Property()
{
JsonSchema schema = new JsonSchema();
schema.Properties = new Dictionary<string, JsonSchema>
{
{
"bar",
new JsonSchema
{
UniqueItems = true
}
}
};
JObject o = new JObject(
new JProperty("bar", new JArray(1, 2, 3, 3))
);
IList<string> errorMessages;
Assert.IsFalse(o.IsValid(schema, out errorMessages));
Assert.AreEqual(1, errorMessages.Count);
}
[Test]
public void Items_Positional()
{
JsonSchema schema = new JsonSchema();
schema.Items = new List<JsonSchema>
{
new JsonSchema { Type = JsonSchemaType.Object },
new JsonSchema { Type = JsonSchemaType.Integer }
};
schema.PositionalItemsValidation = true;
JArray a = new JArray(new JObject(), 1);
IList<string> errorMessages;
Assert.IsTrue(a.IsValid(schema, out errorMessages));
Assert.AreEqual(0, errorMessages.Count);
}
}
}
@@ -59,7 +59,7 @@ namespace Newtonsoft.Json.Tests.Schema
";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("A person", schema.Description);
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
@@ -80,7 +80,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Age", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Integer, schema.Type);
@@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("MultipleItems", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Items[0].Type);
@@ -113,7 +113,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("AdditionalProperties", schema.Description);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Boolean, schema.AdditionalProperties.Type);
@@ -128,7 +128,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Required", schema.Description);
Assert.AreEqual(true, schema.Required);
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(true, schema.ExclusiveMinimum);
Assert.AreEqual(true, schema.ExclusiveMaximum);
@@ -158,7 +158,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("ReadOnly", schema.Description);
Assert.AreEqual(true, schema.ReadOnly);
@@ -173,7 +173,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Hidden", schema.Description);
Assert.AreEqual(true, schema.Hidden);
@@ -188,7 +188,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Id", schema.Description);
Assert.AreEqual("testid", schema.Id);
@@ -203,7 +203,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Title", schema.Description);
Assert.AreEqual("testtitle", schema.Title);
@@ -218,7 +218,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Pattern", schema.Description);
Assert.AreEqual("testpattern", schema.Pattern);
@@ -233,7 +233,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Format", schema.Description);
Assert.AreEqual("testformat", schema.Format);
@@ -248,45 +248,12 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Requires", schema.Description);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Requires);
}
[Test]
public void IdentitySingle()
{
string json = @"{
""description"":""Identity"",
""identity"":""PurpleMonkeyDishwasher""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Identity", schema.Description);
Assert.AreEqual(1, schema.Identity.Count);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Identity[0]);
}
[Test]
public void IdentityMultiple()
{
string json = @"{
""description"":""Identity"",
""identity"":[""PurpleMonkeyDishwasher"",""Antelope""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Identity", schema.Description);
Assert.AreEqual(2, schema.Identity.Count);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Identity[0]);
Assert.AreEqual("Antelope", schema.Identity[1]);
}
[Test]
public void MinimumMaximum()
{
@@ -302,7 +269,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("MinimumMaximum", schema.Description);
Assert.AreEqual(1.1, schema.Minimum);
@@ -323,7 +290,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowSingleType", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Disallow);
@@ -338,7 +305,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowMultipleTypes", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Float, schema.Disallow);
@@ -353,10 +320,10 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultPrimitiveType", schema.Description);
Assert.AreEqual(1.1, (double)schema.Default);
Assert.AreEqual(1.1, (double) schema.Default);
}
[Test]
@@ -368,36 +335,12 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultComplexType", schema.Description);
Assert.IsTrue(JToken.DeepEquals(JObject.Parse(@"{""pie"":true}"), schema.Default));
}
[Test]
public void Options()
{
string json = @"{
""description"":""NZ Island"",
""type"":""string"",
""options"":
[
{""value"":""NI"",""label"":""North Island""},
{""value"":""SI"",""label"":""South Island""}
]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("NZ Island", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Type);
Assert.AreEqual(2, schema.Options.Count);
Assert.AreEqual("North Island", schema.Options[new JValue("NI")]);
Assert.AreEqual("South Island", schema.Options[new JValue("SI")]);
}
[Test]
public void Enum()
{
@@ -408,14 +351,14 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Type", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Array, schema.Type);
Assert.AreEqual(8, schema.Enum.Count);
Assert.AreEqual("string", (string)schema.Enum[0]);
Assert.AreEqual("any", (string)schema.Enum[schema.Enum.Count - 1]);
Assert.AreEqual("string", (string) schema.Enum[0]);
Assert.AreEqual("any", (string) schema.Enum[schema.Enum.Count - 1]);
}
[Test]
@@ -429,7 +372,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("CircularReference", schema.Description);
Assert.AreEqual("CircularReferenceArray", schema.Id);
@@ -441,19 +384,19 @@ namespace Newtonsoft.Json.Tests.Schema
[Test]
public void UnresolvedReference()
{
ExceptionAssert.Throws<Exception>(@"Could not resolve schema reference for Id 'MyUnresolvedReference'.",
() =>
{
string json = @"{
ExceptionAssert.Throws<Exception>(@"Could not resolve schema reference 'MyUnresolvedReference'.",
() =>
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""MyUnresolvedReference""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
});
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
});
}
[Test]
@@ -466,11 +409,161 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.IsNotNull(schema.PatternProperties);
Assert.AreEqual(1, schema.PatternProperties.Count);
Assert.AreEqual("Blah", schema.PatternProperties["[abc]"].Id);
}
[Test]
public void AdditionalItems()
{
string json = @"{
""items"": [],
""additionalItems"": {""type"": ""integer""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.IsNotNull(schema.AdditionalItems);
Assert.AreEqual(JsonSchemaType.Integer, schema.AdditionalItems.Type);
Assert.AreEqual(true, schema.AllowAdditionalItems);
}
[Test]
public void DisallowAdditionalItems()
{
string json = @"{
""items"": [],
""additionalItems"": false
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.IsNull(schema.AdditionalItems);
Assert.AreEqual(false, schema.AllowAdditionalItems);
}
[Test]
public void AllowAdditionalItems()
{
string json = @"{
""items"": {},
""additionalItems"": false
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.IsNull(schema.AdditionalItems);
Assert.AreEqual(false, schema.AllowAdditionalItems);
}
[Test]
public void Location()
{
string json = @"{
""properties"":{
""foo"":{
""type"":""array"",
""items"":[
{
""type"":""integer""
},
{
""properties"":{
""foo"":{
""type"":""integer""
}
}
}
]
}
}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("#", schema.Location);
Assert.AreEqual("#/properties/foo", schema.Properties["foo"].Location);
Assert.AreEqual("#/properties/foo/items/1/properties/foo", schema.Properties["foo"].Items[1].Properties["foo"].Location);
}
[Test]
public void Reference_BackwardsLocation()
{
string json = @"{
""properties"": {
""foo"": {""type"": ""integer""},
""bar"": {""$ref"": ""#/properties/foo""}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]);
}
[Test]
public void Reference_ForwardsLocation()
{
string json = @"{
""properties"": {
""bar"": {""$ref"": ""#/properties/foo""},
""foo"": {""type"": ""integer""}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]);
}
[Test]
public void Reference_NonStandardLocation()
{
string json = @"{
""properties"": {
""bar"": {""$ref"": ""#/common/foo""},
""foo"": {""$ref"": ""#/common/foo""}
},
""common"": {
""foo"": {""type"": ""integer""}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]);
}
[Test]
public void EscapedReferences()
{
string json = @"{
""tilda~field"": {""type"": ""integer""},
""slash/field"": {""type"": ""object""},
""percent%field"": {""type"": ""array""},
""properties"": {
""tilda"": {""$ref"": ""#/tilda~0field""},
""slash"": {""$ref"": ""#/slash~1field""},
""percent"": {""$ref"": ""#/percent%25field""}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["tilda"].Type);
Assert.AreEqual(JsonSchemaType.Object, schema.Properties["slash"].Type);
Assert.AreEqual(JsonSchemaType.Array, schema.Properties["percent"].Type);
}
}
}
@@ -619,20 +619,6 @@ namespace Newtonsoft.Json.Tests.Schema
0,
1,
-1
],
""options"": [
{
""value"": 0,
""label"": ""No""
},
{
""value"": 1,
""label"": ""Asc""
},
{
""value"": -1,
""label"": ""Desc""
}
]
}
}
@@ -25,6 +25,7 @@
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
@@ -62,7 +63,7 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchema second = JsonSchema.Parse(json, resolver);
Assert.AreEqual(first, second.Extends);
Assert.AreEqual(first, second.Extends[0]);
json =
@"{
@@ -73,8 +74,8 @@ namespace Newtonsoft.Json.Tests.Schema
}";
JsonSchema third = JsonSchema.Parse(json, resolver);
Assert.AreEqual(second, third.Extends);
Assert.AreEqual(first, third.Extends.Extends);
Assert.AreEqual(second, third.Extends[0]);
Assert.AreEqual(first, third.Extends[0].Extends[0]);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
@@ -346,43 +347,6 @@ namespace Newtonsoft.Json.Tests.Schema
}", json);
}
[Test]
public void ReadOptions()
{
JsonSchema schema = JsonSchema.Parse(@"{
""type"": ""object"",
""properties"": {
""x"": {
""type"": ""integer"",
""enum"": [
0,
1,
-1
],
""options"": [
{
""value"": 0,
""label"": ""No""
},
{
""value"": 1,
""label"": ""Asc""
},
{
""value"": -1,
""label"": ""Desc""
}
]
}
}
}");
Assert.AreEqual(schema.Properties["x"].Options.Count, 3);
Assert.AreEqual(schema.Properties["x"].Options[0], "No");
Assert.AreEqual(schema.Properties["x"].Options[1], "Asc");
Assert.AreEqual(schema.Properties["x"].Options[-1], "Desc");
}
[Test]
public void WriteTo_ExclusiveMinimum_ExclusiveMaximum()
{
@@ -425,6 +389,86 @@ namespace Newtonsoft.Json.Tests.Schema
""patternProperties"": {
""[abc]"": {}
}
}", json);
}
[Test]
public void ToString_AdditionalItems()
{
JsonSchema schema = JsonSchema.Parse(@"{
""additionalItems"": {""type"": ""integer""}
}");
string json = schema.ToString();
Assert.AreEqual(@"{
""additionalItems"": {
""type"": ""integer""
}
}", json);
}
[Test]
public void WriteTo_PositionalItemsValidation_True()
{
JsonSchema schema = new JsonSchema();
schema.PositionalItemsValidation = true;
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""items"": []
}", json);
}
[Test]
public void WriteTo_PositionalItemsValidation_TrueWithItemsSchema()
{
JsonSchema schema = new JsonSchema();
schema.PositionalItemsValidation = true;
schema.Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String }};
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""items"": [
{
""type"": ""string""
}
]
}", json);
}
[Test]
public void WriteTo_PositionalItemsValidation_FalseWithItemsSchema()
{
JsonSchema schema = new JsonSchema();
schema.Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String } };
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""items"": {
""type"": ""string""
}
}", json);
}
}
@@ -0,0 +1,82 @@
[
{
"description": "additionalItems as schema",
"schema": {
"items": [],
"additionalItems": {"type": "integer"}
},
"tests": [
{
"description": "additional items match schema",
"data": [ 1, 2, 3, 4 ],
"valid": true
},
{
"description": "additional items do not match schema",
"data": [ 1, 2, 3, "foo" ],
"valid": false
}
]
},
{
"description": "items is schema, no additionalItems",
"schema": {
"items": {},
"additionalItems": false
},
"tests": [
{
"description": "all items match schema",
"data": [ 1, 2, 3, 4, 5 ],
"valid": true
}
]
},
{
"description": "array of items with no additionalItems",
"schema": {
"items": [{}, {}, {}],
"additionalItems": false
},
"tests": [
{
"description": "no additional items present",
"data": [ 1, 2, 3 ],
"valid": true
},
{
"description": "additional items are not permitted",
"data": [ 1, 2, 3, 4 ],
"valid": false
}
]
},
{
"description": "additionalItems as false without items",
"schema": {"additionalItems": false},
"tests": [
{
"description":
"items defaults to empty schema so everything is valid",
"data": [ 1, 2, 3, 4, 5 ],
"valid": true
},
{
"description": "ignores non-arrays",
"data": {"foo" : "bar"},
"valid": true
}
]
},
{
"description": "additionalItems are allowed by default",
"schema": {"items": []},
"tests": [
{
"description": "only the first items are validated",
"data": [1, "foo", false],
"valid": true
}
]
}
]
@@ -0,0 +1,63 @@
[
{
"description":
"additionalProperties being false does not allow other properties",
"schema": {
"properties": {"foo": {}, "bar": {}},
"additionalProperties": false
},
"tests": [
{
"description": "no additional properties is valid",
"data": {"foo": 1},
"valid": true
},
{
"description": "an additional property is invalid",
"data": {"foo" : 1, "bar" : 2, "quux" : "boom"},
"valid": false
},
{
"description": "ignores non-objects",
"data": [1, 2, 3],
"valid": true
}
]
},
{
"description":
"additionalProperties allows a schema which should validate",
"schema": {
"properties": {"foo": {}, "bar": {}},
"additionalProperties": {"type": "boolean"}
},
"tests": [
{
"description": "no additional properties is valid",
"data": {"foo": 1},
"valid": true
},
{
"description": "an additional valid property is valid",
"data": {"foo" : 1, "bar" : 2, "quux" : true},
"valid": true
},
{
"description": "an additional invalid property is invalid",
"data": {"foo" : 1, "bar" : 2, "quux" : 12},
"valid": false
}
]
},
{
"description": "additionalProperties are allowed by default",
"schema": {"properties": {"foo": {}, "bar": {}}},
"tests": [
{
"description": "additional properties are allowed",
"data": {"foo": 1, "bar": 2, "quux": true},
"valid": true
}
]
}
]
@@ -0,0 +1,108 @@
[
{
"description": "dependencies",
"schema": {
"dependencies": {"bar": "foo"}
},
"tests": [
{
"description": "neither",
"data": {},
"valid": true
},
{
"description": "nondependant",
"data": {"foo": 1},
"valid": true
},
{
"description": "with dependency",
"data": {"foo": 1, "bar": 2},
"valid": true
},
{
"description": "missing dependency",
"data": {"bar": 2},
"valid": false
},
{
"description": "ignores non-objects",
"data": "foo",
"valid": true
}
]
},
{
"description": "multiple dependencies",
"schema": {
"dependencies": {"quux": ["foo", "bar"]}
},
"tests": [
{
"description": "neither",
"data": {},
"valid": true
},
{
"description": "nondependants",
"data": {"foo": 1, "bar": 2},
"valid": true
},
{
"description": "with dependencies",
"data": {"foo": 1, "bar": 2, "quux": 3},
"valid": true
},
{
"description": "missing dependency",
"data": {"foo": 1, "quux": 2},
"valid": false
},
{
"description": "missing other dependency",
"data": {"bar": 1, "quux": 2},
"valid": false
},
{
"description": "missing both dependencies",
"data": {"quux": 1},
"valid": false
}
]
},
{
"description": "multiple dependencies subschema",
"schema": {
"dependencies": {
"bar": {
"properties": {
"foo": {"type": "integer"},
"bar": {"type": "integer"}
}
}
}
},
"tests": [
{
"description": "valid",
"data": {"foo": 1, "bar": 2},
"valid": true
},
{
"description": "wrong type",
"data": {"foo": "quux", "bar": 2},
"valid": false
},
{
"description": "wrong type other",
"data": {"foo": 2, "bar": "quux"},
"valid": false
},
{
"description": "wrong type both",
"data": {"foo": "quux", "bar": "quux"},
"valid": false
}
]
}
]
@@ -0,0 +1,80 @@
[
{
"description": "disallow",
"schema": {
"disallow": "integer"
},
"tests": [
{
"description": "allowed",
"data": "foo",
"valid": true
},
{
"description": "disallowed",
"data": 1,
"valid": false
}
]
},
{
"description": "multiple disallow",
"schema": {
"disallow": ["integer", "boolean"]
},
"tests": [
{
"description": "valid",
"data": "foo",
"valid": true
},
{
"description": "mismatch",
"data": 1,
"valid": false
},
{
"description": "other mismatch",
"data": true,
"valid": false
}
]
},
{
"description": "multiple disallow subschema",
"schema": {
"disallow":
["string",
{
"type": "object",
"properties": {
"foo": {
"type": "string"
}
}
}]
},
"tests": [
{
"description": "match",
"data": 1,
"valid": true
},
{
"description": "other match",
"data": {"foo": 1},
"valid": true
},
{
"description": "mismatch",
"data": "foo",
"valid": false
},
{
"description": "other mismatch",
"data": {"foo": "bar"},
"valid": false
}
]
}
]
@@ -0,0 +1,60 @@
[
{
"description": "by int",
"schema": {"divisibleBy": 2},
"tests": [
{
"description": "int by int",
"data": 10,
"valid": true
},
{
"description": "int by int fail",
"data": 7,
"valid": false
},
{
"description": "ignores non-numbers",
"data": "foo",
"valid": true
}
]
},
{
"description": "by number",
"schema": {"divisibleBy": 1.5},
"tests": [
{
"description": "zero is divisible by anything (except 0)",
"data": 0,
"valid": true
},
{
"description": "4.5 is divisible by 1.5",
"data": 4.5,
"valid": true
},
{
"description": "35 is not divisible by 1.5",
"data": 35,
"valid": false
}
]
},
{
"description": "by small number",
"schema": {"divisibleBy": 0.0001},
"tests": [
{
"description": "0.0075 is divisible by 0.0001",
"data": 0.0075,
"valid": true
},
{
"description": "0.00751 is not divisible by 0.0001",
"data": 0.00751,
"valid": false
}
]
}
]
@@ -0,0 +1,39 @@
[
{
"description": "simple enum validation",
"schema": {"enum": [1, 2, 3]},
"tests": [
{
"description": "one of the enum is valid",
"data": 1,
"valid": true
},
{
"description": "something else is invalid",
"data": 4,
"valid": false
}
]
},
{
"description": "heterogeneous enum validation",
"schema": {"enum": [6, "foo", [], true, {"foo": 12}]},
"tests": [
{
"description": "one of the enum is valid",
"data": [],
"valid": true
},
{
"description": "something else is invalid",
"data": null,
"valid": false
},
{
"description": "objects are deep compared",
"data": {"foo": false},
"valid": false
}
]
}
]
@@ -0,0 +1,94 @@
[
{
"description": "extends",
"schema": {
"properties": {"bar": {"type": "integer", "required": true}},
"extends": {
"properties": {
"foo": {"type": "string", "required": true}
}
}
},
"tests": [
{
"description": "extends",
"data": {"foo": "baz", "bar": 2},
"valid": true
},
{
"description": "mismatch extends",
"data": {"foo": "baz"},
"valid": false
},
{
"description": "mismatch extended",
"data": {"bar": 2},
"valid": false
},
{
"description": "wrong type",
"data": {"foo": "baz", "bar": "quux"},
"valid": false
}
]
},
{
"description": "multiple extends",
"schema": {
"properties": {"bar": {"type": "integer", "required": true}},
"extends" : [
{
"properties": {
"foo": {"type": "string", "required": true}
}
},
{
"properties": {
"baz": {"type": "null", "required": true}
}
}
]
},
"tests": [
{
"description": "valid",
"data": {"foo": "quux", "bar": 2, "baz": null},
"valid": true
},
{
"description": "mismatch first extends",
"data": {"bar": 2, "baz": null},
"valid": false
},
{
"description": "mismatch second extends",
"data": {"foo": "quux", "bar": 2},
"valid": false
},
{
"description": "mismatch both",
"data": {"bar": 2},
"valid": false
}
]
},
{
"description": "extends simple types",
"schema": {
"minimum": 20,
"extends": {"maximum": 30}
},
"tests": [
{
"description": "valid",
"data": 25,
"valid": true
},
{
"description": "mismatch extends",
"data": 35,
"valid": false
}
]
}
]
@@ -0,0 +1,46 @@
[
{
"description": "a schema given for items",
"schema": {
"items": {"type": "integer"}
},
"tests": [
{
"description": "valid items",
"data": [ 1, 2, 3 ],
"valid": true
},
{
"description": "wrong type of items",
"data": [1, "x"],
"valid": false
},
{
"description": "ignores non-arrays",
"data": {"foo" : "bar"},
"valid": true
}
]
},
{
"description": "an array of schemas for items",
"schema": {
"items": [
{"type": "integer"},
{"type": "string"}
]
},
"tests": [
{
"description": "correct types",
"data": [ 1, "foo" ],
"valid": true
},
{
"description": "wrong types",
"data": [ "foo", 1 ],
"valid": false
}
]
}
]
@@ -0,0 +1,28 @@
[
{
"description": "maxItems validation",
"schema": {"maxItems": 2},
"tests": [
{
"description": "shorter is valid",
"data": [1],
"valid": true
},
{
"description": "exact length is valid",
"data": [1, 2],
"valid": true
},
{
"description": "too long is invalid",
"data": [1, 2, 3],
"valid": false
},
{
"description": "ignores non-arrays",
"data": "foobar",
"valid": true
}
]
}
]
@@ -0,0 +1,28 @@
[
{
"description": "maxLength validation",
"schema": {"maxLength": 2},
"tests": [
{
"description": "shorter is valid",
"data": "f",
"valid": true
},
{
"description": "exact length is valid",
"data": "fo",
"valid": true
},
{
"description": "too long is invalid",
"data": "foo",
"valid": false
},
{
"description": "ignores non-strings",
"data": 10,
"valid": true
}
]
}
]
@@ -0,0 +1,42 @@
[
{
"description": "maximum validation",
"schema": {"maximum": 3.0},
"tests": [
{
"description": "below the maximum is valid",
"data": 2.6,
"valid": true
},
{
"description": "above the maximum is invalid",
"data": 3.5,
"valid": false
},
{
"description": "ignores non-numbers",
"data": "x",
"valid": true
}
]
},
{
"description": "exclusiveMaximum validation",
"schema": {
"maximum": 3.0,
"exclusiveMaximum": true
},
"tests": [
{
"description": "below the maximum is still valid",
"data": 2.2,
"valid": true
},
{
"description": "boundary point is invalid",
"data": 3.0,
"valid": false
}
]
}
]
@@ -0,0 +1,28 @@
[
{
"description": "minItems validation",
"schema": {"minItems": 1},
"tests": [
{
"description": "longer is valid",
"data": [1, 2],
"valid": true
},
{
"description": "exact length is valid",
"data": [1],
"valid": true
},
{
"description": "too short is invalid",
"data": [],
"valid": false
},
{
"description": "ignores non-arrays",
"data": "",
"valid": true
}
]
}
]
@@ -0,0 +1,28 @@
[
{
"description": "minLength validation",
"schema": {"minLength": 2},
"tests": [
{
"description": "longer is valid",
"data": "foo",
"valid": true
},
{
"description": "exact length is valid",
"data": "fo",
"valid": true
},
{
"description": "too short is invalid",
"data": "f",
"valid": false
},
{
"description": "ignores non-strings",
"data": 1,
"valid": true
}
]
}
]
@@ -0,0 +1,42 @@
[
{
"description": "minimum validation",
"schema": {"minimum": 1.1},
"tests": [
{
"description": "above the minimum is valid",
"data": 2.6,
"valid": true
},
{
"description": "below the minimum is invalid",
"data": 0.6,
"valid": false
},
{
"description": "ignores non-numbers",
"data": "x",
"valid": true
}
]
},
{
"description": "exclusiveMinimum validation",
"schema": {
"minimum": 1.1,
"exclusiveMinimum": true
},
"tests": [
{
"description": "above the minimum is still valid",
"data": 1.2,
"valid": true
},
{
"description": "boundary point is invalid",
"data": 1.1,
"valid": false
}
]
}
]
@@ -0,0 +1,23 @@
[
{
"description": "pattern validation",
"schema": {"pattern": "^a*$"},
"tests": [
{
"description": "a matching pattern is valid",
"data": "aaa",
"valid": true
},
{
"description": "a non-matching pattern is invalid",
"data": "abc",
"valid": false
},
{
"description": "ignores non-strings",
"data": true,
"valid": true
}
]
}
]
@@ -0,0 +1,79 @@
[
{
"description":
"patternProperties validates properties matching a regex",
"schema": {
"patternProperties": {
"f.*o": {"type": "integer"}
}
},
"tests": [
{
"description": "a single valid match is valid",
"data": {"foo": 1},
"valid": true
},
{
"description": "multiple valid matches is valid",
"data": {"foo": 1, "foooooo" : 2},
"valid": true
},
{
"description": "a single invalid match is invalid",
"data": {"foo": "bar", "fooooo": 2},
"valid": false
},
{
"description": "multiple invalid matches is invalid",
"data": {"foo": "bar", "foooooo" : "baz"},
"valid": false
},
{
"description": "ignores non-objects",
"data": 12,
"valid": true
}
]
},
{
"description": "multiple simultaneous patternProperties are validated",
"schema": {
"patternProperties": {
"a*": {"type": "integer"},
"aaa*": {"maximum": 20}
}
},
"tests": [
{
"description": "a single valid match is valid",
"data": {"a": 21},
"valid": true
},
{
"description": "a simultaneous match is valid",
"data": {"aaaa": 18},
"valid": true
},
{
"description": "multiple matches is valid",
"data": {"a": 21, "aaaa": 18},
"valid": true
},
{
"description": "an invalid due to one is invalid",
"data": {"a": "bar"},
"valid": false
},
{
"description": "an invalid due to the other is invalid",
"data": {"aaaa": 31},
"valid": false
},
{
"description": "an invalid due to both is invalid",
"data": {"aaa": "foo", "aaaa": 31},
"valid": false
}
]
}
]
@@ -0,0 +1,92 @@
[
{
"description": "object properties validation",
"schema": {
"properties": {
"foo": {"type": "integer"},
"bar": {"type": "string"}
}
},
"tests": [
{
"description": "both properties present and valid is valid",
"data": {"foo": 1, "bar": "baz"},
"valid": true
},
{
"description": "one property invalid is invalid",
"data": {"foo": 1, "bar": {}},
"valid": false
},
{
"description": "both properties invalid is invalid",
"data": {"foo": [], "bar": {}},
"valid": false
},
{
"description": "doesn't invalidate other properties",
"data": {"quux": []},
"valid": true
},
{
"description": "ignores non-objects",
"data": [],
"valid": true
}
]
},
{
"description":
"properties, patternProperties, additionalProperties interaction",
"schema": {
"properties": {
"foo": {"type": "array", "maxItems": 3},
"bar": {"type": "array"}
},
"patternProperties": {"f.o": {"minItems": 2}},
"additionalProperties": {"type": "integer"}
},
"tests": [
{
"description": "property validates property",
"data": {"foo": [1, 2]},
"valid": true
},
{
"description": "property invalidates property",
"data": {"foo": [1, 2, 3, 4]},
"valid": false
},
{
"description": "patternProperty invalidates property",
"data": {"foo": []},
"valid": false
},
{
"description": "patternProperty validates nonproperty",
"data": {"fxo": [1, 2]},
"valid": true
},
{
"description": "patternProperty invalidates nonproperty",
"data": {"fxo": []},
"valid": false
},
{
"description": "additionalProperty ignores property",
"data": {"bar": []},
"valid": true
},
{
"description": "additionalProperty validates others",
"data": {"quux": 3},
"valid": true
},
{
"description": "additionalProperty invalidates others",
"data": {"quux": "foo"},
"valid": false
}
]
}
]
@@ -0,0 +1,84 @@
[
{
"description": "root pointer ref",
"schema": {
"properties": {
"foo": {"$ref": "#"}
},
"additionalProperties": false
},
"tests": [
{
"description": "match",
"data": {"foo": false},
"valid": true
},
{
"description": "recursive match",
"data": {"foo": {"foo": false}},
"valid": true
},
{
"description": "mismatch",
"data": {"bar": false},
"valid": false
},
{
"description": "recursive mismatch",
"data": {"foo": {"bar": false}},
"valid": false
}
]
},
{
"description": "relative pointer ref",
"schema": {
"properties": {
"foo": {"type": "integer"},
"bar": {"$ref": "#/properties/foo"}
}
},
"tests": [
{
"description": "match",
"data": {"bar": 3},
"valid": true
},
{
"description": "mismatch",
"data": {"bar": true},
"valid": false
}
]
},
{
"description": "escaped pointer ref",
"schema": {
"tilda~field": {"type": "integer"},
"slash/field": {"type": "integer"},
"percent%field": {"type": "integer"},
"properties": {
"tilda": {"$ref": "#/tilda~0field"},
"slash": {"$ref": "#/slash~1field"},
"percent": {"$ref": "#/percent%25field"}
}
},
"tests": [
{
"description": "slash",
"data": {"slash": "aoeu"},
"valid": false
},
{
"description": "tilda",
"data": {"tilda": "aoeu"},
"valid": false
},
{
"description": "percent",
"data": {"percent": "aoeu"},
"valid": false
}
]
}
]
@@ -0,0 +1,53 @@
[
{
"description": "required validation",
"schema": {
"properties": {
"foo": {"required" : true},
"bar": {}
}
},
"tests": [
{
"description": "present required property is valid",
"data": {"foo": 1},
"valid": true
},
{
"description": "non-present required property is invalid",
"data": {"bar": 1},
"valid": false
}
]
},
{
"description": "required default validation",
"schema": {
"properties": {
"foo": {}
}
},
"tests": [
{
"description": "not required by default",
"data": {},
"valid": true
}
]
},
{
"description": "required explicitly false validation",
"schema": {
"properties": {
"foo": {"required": false}
}
},
"tests": [
{
"description": "not required if required is false",
"data": {},
"valid": true
}
]
}
]
@@ -0,0 +1,479 @@
[
{
"description": "integer type matches integers",
"schema": {"type": "integer"},
"tests": [
{
"description": "an integer is an integer",
"data": 1,
"valid": true
},
{
"description": "a float is not an integer",
"data": 1.1,
"valid": false
},
{
"description": "a float is not an integer even without fractional part",
"data": 1.0,
"valid": false
},
{
"description": "a string is not an integer",
"data": "foo",
"valid": false
},
{
"description": "an object is not an integer",
"data": {},
"valid": false
},
{
"description": "an array is not an integer",
"data": [],
"valid": false
},
{
"description": "a boolean is not an integer",
"data": true,
"valid": false
},
{
"description": "null is not an integer",
"data": null,
"valid": false
}
]
},
{
"description": "number type matches numbers",
"schema": {"type": "number"},
"tests": [
{
"description": "an integer is a number",
"data": 1,
"valid": true
},
{
"description": "a float is a number",
"data": 1.1,
"valid": true
},
{
"description": "a string is not a number",
"data": "foo",
"valid": false
},
{
"description": "an object is not a number",
"data": {},
"valid": false
},
{
"description": "an array is not a number",
"data": [],
"valid": false
},
{
"description": "a boolean is not a number",
"data": true,
"valid": false
},
{
"description": "null is not a number",
"data": null,
"valid": false
}
]
},
{
"description": "string type matches strings",
"schema": {"type": "string"},
"tests": [
{
"description": "1 is not a string",
"data": 1,
"valid": false
},
{
"description": "a float is not a string",
"data": 1.1,
"valid": false
},
{
"description": "a string is a string",
"data": "foo",
"valid": true
},
{
"description": "an object is not a string",
"data": {},
"valid": false
},
{
"description": "an array is not a string",
"data": [],
"valid": false
},
{
"description": "a boolean is not a string",
"data": true,
"valid": false
},
{
"description": "null is not a string",
"data": null,
"valid": false
}
]
},
{
"description": "object type matches objects",
"schema": {"type": "object"},
"tests": [
{
"description": "an integer is not an object",
"data": 1,
"valid": false
},
{
"description": "a float is not an object",
"data": 1.1,
"valid": false
},
{
"description": "a string is not an object",
"data": "foo",
"valid": false
},
{
"description": "an object is an object",
"data": {},
"valid": true
},
{
"description": "an array is not an object",
"data": [],
"valid": false
},
{
"description": "a boolean is not an object",
"data": true,
"valid": false
},
{
"description": "null is not an object",
"data": null,
"valid": false
}
]
},
{
"description": "array type matches arrays",
"schema": {"type": "array"},
"tests": [
{
"description": "an integer is not an array",
"data": 1,
"valid": false
},
{
"description": "a float is not an array",
"data": 1.1,
"valid": false
},
{
"description": "a string is not an array",
"data": "foo",
"valid": false
},
{
"description": "an object is not an array",
"data": {},
"valid": false
},
{
"description": "an array is not an array",
"data": [],
"valid": true
},
{
"description": "a boolean is not an array",
"data": true,
"valid": false
},
{
"description": "null is not an array",
"data": null,
"valid": false
}
]
},
{
"description": "boolean type matches booleans",
"schema": {"type": "boolean"},
"tests": [
{
"description": "an integer is not a boolean",
"data": 1,
"valid": false
},
{
"description": "a float is not a boolean",
"data": 1.1,
"valid": false
},
{
"description": "a string is not a boolean",
"data": "foo",
"valid": false
},
{
"description": "an object is not a boolean",
"data": {},
"valid": false
},
{
"description": "an array is not a boolean",
"data": [],
"valid": false
},
{
"description": "a boolean is not a boolean",
"data": true,
"valid": true
},
{
"description": "null is not a boolean",
"data": null,
"valid": false
}
]
},
{
"description": "null type matches only the null object",
"schema": {"type": "null"},
"tests": [
{
"description": "an integer is not null",
"data": 1,
"valid": false
},
{
"description": "a float is not null",
"data": 1.1,
"valid": false
},
{
"description": "a string is not null",
"data": "foo",
"valid": false
},
{
"description": "an object is not null",
"data": {},
"valid": false
},
{
"description": "an array is not null",
"data": [],
"valid": false
},
{
"description": "a boolean is not null",
"data": true,
"valid": false
},
{
"description": "null is null",
"data": null,
"valid": true
}
]
},
{
"description": "any type matches any type",
"schema": {"type": "any"},
"tests": [
{
"description": "any type includes integers",
"data": 1,
"valid": true
},
{
"description": "any type includes float",
"data": 1.1,
"valid": true
},
{
"description": "any type includes string",
"data": "foo",
"valid": true
},
{
"description": "any type includes object",
"data": {},
"valid": true
},
{
"description": "any type includes array",
"data": [],
"valid": true
},
{
"description": "any type includes boolean",
"data": true,
"valid": true
},
{
"description": "any type includes null",
"data": null,
"valid": true
}
]
},
{
"description": "multiple types can be specified in an array",
"schema": {"type": ["integer", "string"]},
"tests": [
{
"description": "an integer is valid",
"data": 1,
"valid": true
},
{
"description": "a string is valid",
"data": "foo",
"valid": true
},
{
"description": "a float is invalid",
"data": 1.1,
"valid": false
},
{
"description": "an object is invalid",
"data": {},
"valid": false
},
{
"description": "an array is invalid",
"data": [],
"valid": false
},
{
"description": "a boolean is invalid",
"data": true,
"valid": false
},
{
"description": "null is invalid",
"data": null,
"valid": false
}
]
},
{
"description": "types can include schemas",
"schema": {
"type": [
"array",
{"type": "object"}
]
},
"tests": [
{
"description": "an integer is invalid",
"data": 1,
"valid": false
},
{
"description": "a string is invalid",
"data": "foo",
"valid": false
},
{
"description": "a float is invalid",
"data": 1.1,
"valid": false
},
{
"description": "an object is valid",
"data": {},
"valid": true
},
{
"description": "an array is valid",
"data": [],
"valid": true
},
{
"description": "a boolean is invalid",
"data": true,
"valid": false
},
{
"description": "null is invalid",
"data": null,
"valid": false
}
]
},
{
"description":
"when types includes a schema it should fully validate the schema",
"schema": {
"type": [
"integer",
{
"properties": {
"foo": {"type": "null"}
}
}
]
},
"tests": [
{
"description": "an integer is valid",
"data": 1,
"valid": true
},
{
"description": "an object is valid only if it is fully valid",
"data": {"foo": null},
"valid": true
},
{
"description": "an object is invalid otherwise",
"data": {"foo": "bar"},
"valid": false
}
]
},
{
"description": "types from separate schemas are merged",
"schema": {
"type": [
{"type": ["string"]},
{"type": ["array", "null"]}
]
},
"tests": [
{
"description": "an integer is invalid",
"data": 1,
"valid": false
},
{
"description": "a string is valid",
"data": "foo",
"valid": true
},
{
"description": "an array is valid",
"data": [1, 2, 3],
"valid": true
}
]
}
]
@@ -0,0 +1,79 @@
[
{
"description": "uniqueItems validation",
"schema": {"uniqueItems": true},
"tests": [
{
"description": "unique array of integers is valid",
"data": [1, 2],
"valid": true
},
{
"description": "non-unique array of integers is invalid",
"data": [1, 1],
"valid": false
},
{
"description": "numbers are unique if mathematically unequal",
"data": [1.0, 1.00, 1],
"valid": false
},
{
"description": "unique array of objects is valid",
"data": [{"foo": "bar"}, {"foo": "baz"}],
"valid": true
},
{
"description": "non-unique array of objects is invalid",
"data": [{"foo": "bar"}, {"foo": "bar"}],
"valid": false
},
{
"description": "unique array of nested objects is valid",
"data": [
{"foo": {"bar" : {"baz" : true}}},
{"foo": {"bar" : {"baz" : false}}}
],
"valid": true
},
{
"description": "non-unique array of nested objects is invalid",
"data": [
{"foo": {"bar" : {"baz" : true}}},
{"foo": {"bar" : {"baz" : true}}}
],
"valid": false
},
{
"description": "unique array of arrays is valid",
"data": [["foo"], ["bar"]],
"valid": true
},
{
"description": "non-unique array of arrays is invalid",
"data": [["foo"], ["foo"]],
"valid": false
},
{
"description": "1 and true are unique",
"data": [1, true],
"valid": true
},
{
"description": "0 and false are unique",
"data": [0, false],
"valid": true
},
{
"description": "unique heterogeneous types are valid",
"data": [{}, [1], true, null, 1],
"valid": true
},
{
"description": "non-unique heterogeneous types are invalid",
"data": [{}, [1], true, null, {}, 1],
"valid": false
}
]
}
]
+1 -1
View File
@@ -129,7 +129,7 @@ namespace Newtonsoft.Json.Tests
catch (TException ex)
{
if (message != null)
Assert.AreEqual(message, ex.Message, "Unexpected exception message." + Environment.NewLine + "Expected: " + message + Environment.NewLine + "Got: " + ex.Message);
Assert.AreEqual(message, ex.Message, "Unexpected exception message." + Environment.NewLine + "Expected: " + message + Environment.NewLine + "Got: " + ex.Message + Environment.NewLine + Environment.NewLine + ex);
}
catch (Exception ex)
{
+7
View File
@@ -81,5 +81,12 @@ namespace Newtonsoft.Json
{
}
#endif
internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
return new JsonException(message);
}
}
}
@@ -90,7 +90,7 @@ namespace Newtonsoft.Json
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
internal static new JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
+128 -39
View File
@@ -52,6 +52,10 @@ namespace Newtonsoft.Json
public string CurrentPropertyName { get; set; }
public int ArrayItemCount { get; set; }
public bool IsUniqueArray { get; set; }
public bool IsEnum { get; set; }
public IList<JToken> UniqueArrayItems { get; set; }
public JTokenWriter CurrentItemWriter { get; set; }
public IList<JsonSchemaModel> Schemas
{
@@ -74,6 +78,12 @@ namespace Newtonsoft.Json
_schemas = schemas;
_requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false);
if (tokenType == JTokenType.Array && schemas.Any(s => s.UniqueItems))
{
IsUniqueArray = true;
UniqueArrayItems = new List<JToken>();
}
}
private IEnumerable<string> GetRequiredProperties(JsonSchemaModel schema)
@@ -83,6 +93,7 @@ namespace Newtonsoft.Json
return schema.Properties.Where(p => p.Value.Required).Select(p => p.Key);
}
}
private readonly JsonReader _reader;
@@ -97,7 +108,7 @@ namespace Newtonsoft.Json
public event ValidationEventHandler ValidationEventHandler;
/// <summary>
/// Gets the text value of the current Json token.
/// Gets the text value of the current JSON token.
/// </summary>
/// <value></value>
public override object Value
@@ -133,7 +144,7 @@ namespace Newtonsoft.Json
}
/// <summary>
/// Gets the type of the current Json token.
/// Gets the type of the current JSON token.
/// </summary>
/// <value></value>
public override JsonToken TokenType
@@ -142,7 +153,7 @@ namespace Newtonsoft.Json
}
/// <summary>
/// Gets the Common Language Runtime (CLR) type for the current Json token.
/// Gets the Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
/// <value></value>
public override Type ValueType
@@ -166,12 +177,14 @@ namespace Newtonsoft.Json
return poppedScope;
}
private IEnumerable<JsonSchemaModel> CurrentSchemas
private IList<JsonSchemaModel> CurrentSchemas
{
get { return _currentScope.Schemas; }
}
private IEnumerable<JsonSchemaModel> CurrentMemberSchemas
private static readonly IList<JsonSchemaModel> EmptySchemaList = new List<JsonSchemaModel>();
private IList<JsonSchemaModel> CurrentMemberSchemas
{
get
{
@@ -179,7 +192,7 @@ namespace Newtonsoft.Json
return new List<JsonSchemaModel>(new [] { _model });
if (_currentScope.Schemas == null || _currentScope.Schemas.Count == 0)
return Enumerable.Empty<JsonSchemaModel>();
return EmptySchemaList;
switch (_currentScope.TokenType)
{
@@ -219,30 +232,31 @@ namespace Newtonsoft.Json
case JTokenType.Array:
{
IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>();
foreach (JsonSchemaModel schema in CurrentSchemas)
{
if (!CollectionUtils.IsNullOrEmpty(schema.Items))
if (!schema.PositionalItemsValidation)
{
if (schema.Items.Count == 1)
{
if (schema.Items != null && schema.Items.Count > 0)
schemas.Add(schema.Items[0]);
}
else
}
else
{
if (schema.Items != null && schema.Items.Count > 0)
{
if (schema.Items.Count > (_currentScope.ArrayItemCount - 1))
schemas.Add(schema.Items[_currentScope.ArrayItemCount - 1]);
}
}
if (schema.AllowAdditionalProperties && schema.AdditionalProperties != null)
schemas.Add(schema.AdditionalProperties);
if (schema.AllowAdditionalItems && schema.AdditionalItems != null)
schemas.Add(schema.AdditionalItems);
}
}
return schemas;
}
case JTokenType.Constructor:
return Enumerable.Empty<JsonSchemaModel>();
return EmptySchemaList;
default:
throw new ArgumentOutOfRangeException("TokenType", "Unexpected token type: {0}".FormatWith(CultureInfo.InvariantCulture, _currentScope.TokenType));
}
@@ -307,23 +321,11 @@ namespace Newtonsoft.Json
get { return _reader; }
}
private void ValidateInEnumAndNotDisallowed(JsonSchemaModel schema)
private void ValidateNotDisallowed(JsonSchemaModel schema)
{
if (schema == null)
return;
JToken value = new JValue(_reader.Value);
if (schema.Enum != null)
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
value.WriteTo(new JsonTextWriter(sw));
if (!schema.Enum.ContainsValue(value, new JTokenEqualityComparer()))
RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, sw.ToString()),
schema);
}
JsonSchemaType? currentNodeType = GetCurrentNodeSchemaType();
if (currentNodeType != null)
{
@@ -456,6 +458,9 @@ namespace Newtonsoft.Json
{
JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder();
_model = builder.Build(_schema);
if (!JsonWriter.IsStartToken(_reader.TokenType))
Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas));
}
switch (_reader.TokenType)
@@ -464,25 +469,32 @@ namespace Newtonsoft.Json
ProcessValue();
IList<JsonSchemaModel> objectSchemas = CurrentMemberSchemas.Where(ValidateObject).ToList();
Push(new SchemaScope(JTokenType.Object, objectSchemas));
WriteToken(CurrentSchemas);
break;
case JsonToken.StartArray:
ProcessValue();
IList<JsonSchemaModel> arraySchemas = CurrentMemberSchemas.Where(ValidateArray).ToList();
Push(new SchemaScope(JTokenType.Array, arraySchemas));
WriteToken(CurrentSchemas);
break;
case JsonToken.StartConstructor:
ProcessValue();
Push(new SchemaScope(JTokenType.Constructor, null));
WriteToken(CurrentSchemas);
break;
case JsonToken.PropertyName:
WriteToken(CurrentSchemas);
foreach (JsonSchemaModel schema in CurrentSchemas)
{
ValidatePropertyName(schema);
}
break;
case JsonToken.Raw:
ProcessValue();
break;
case JsonToken.Integer:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateInteger(schema);
@@ -490,6 +502,7 @@ namespace Newtonsoft.Json
break;
case JsonToken.Float:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateFloat(schema);
@@ -497,6 +510,7 @@ namespace Newtonsoft.Json
break;
case JsonToken.String:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateString(schema);
@@ -504,6 +518,7 @@ namespace Newtonsoft.Json
break;
case JsonToken.Boolean:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateBoolean(schema);
@@ -511,14 +526,14 @@ namespace Newtonsoft.Json
break;
case JsonToken.Null:
ProcessValue();
WriteToken(CurrentMemberSchemas);
foreach (JsonSchemaModel schema in CurrentMemberSchemas)
{
ValidateNull(schema);
}
break;
case JsonToken.Undefined:
break;
case JsonToken.EndObject:
WriteToken(CurrentSchemas);
foreach (JsonSchemaModel schema in CurrentSchemas)
{
ValidateEndObject(schema);
@@ -526,6 +541,7 @@ namespace Newtonsoft.Json
Pop();
break;
case JsonToken.EndArray:
WriteToken(CurrentSchemas);
foreach (JsonSchemaModel schema in CurrentSchemas)
{
ValidateEndArray(schema);
@@ -533,11 +549,14 @@ namespace Newtonsoft.Json
Pop();
break;
case JsonToken.EndConstructor:
WriteToken(CurrentSchemas);
Pop();
break;
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
// these have no equivalent in JSON schema
WriteToken(CurrentMemberSchemas);
break;
case JsonToken.None:
// no content, do nothing
@@ -547,6 +566,60 @@ namespace Newtonsoft.Json
}
}
private void WriteToken(IList<JsonSchemaModel> schemas)
{
foreach (SchemaScope schemaScope in _stack)
{
bool isInUniqueArray = (schemaScope.TokenType == JTokenType.Array && schemaScope.IsUniqueArray && schemaScope.ArrayItemCount > 0);
if (isInUniqueArray || schemaScope.IsEnum || schemas.Any(s => s.Enum != null))
{
if (schemaScope.CurrentItemWriter == null)
{
if (JsonWriter.IsEndToken(_reader.TokenType))
continue;
schemaScope.CurrentItemWriter = new JTokenWriter();
}
schemaScope.CurrentItemWriter.WriteToken(_reader, false);
// finished writing current item
if (schemaScope.CurrentItemWriter.Top == 0 && _reader.TokenType != JsonToken.PropertyName)
{
JToken finishedItem = schemaScope.CurrentItemWriter.Token;
// start next item with new writer
schemaScope.CurrentItemWriter = null;
if (isInUniqueArray)
{
if (schemaScope.UniqueArrayItems.Contains(finishedItem, JToken.EqualityComparer))
RaiseError("Non-unique array item at index {0}.".FormatWith(CultureInfo.InvariantCulture, schemaScope.ArrayItemCount - 1), schemaScope.Schemas.First(s => s.UniqueItems));
schemaScope.UniqueArrayItems.Add(finishedItem);
}
else if (schemaScope.IsEnum || schemas.Any(s => s.Enum != null))
{
foreach (JsonSchemaModel schema in schemas)
{
if (schema.Enum != null)
{
if (!schema.Enum.ContainsValue(finishedItem, JToken.EqualityComparer))
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
finishedItem.WriteTo(new JsonTextWriter(sw));
RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, sw.ToString()), schema);
}
}
}
}
}
}
}
}
private void ValidateEndObject(JsonSchemaModel schema)
{
if (schema == null)
@@ -586,7 +659,7 @@ namespace Newtonsoft.Json
if (!TestType(schema, JsonSchemaType.Null))
return;
ValidateInEnumAndNotDisallowed(schema);
ValidateNotDisallowed(schema);
}
private void ValidateBoolean(JsonSchemaModel schema)
@@ -597,7 +670,7 @@ namespace Newtonsoft.Json
if (!TestType(schema, JsonSchemaType.Boolean))
return;
ValidateInEnumAndNotDisallowed(schema);
ValidateNotDisallowed(schema);
}
private void ValidateString(JsonSchemaModel schema)
@@ -608,7 +681,7 @@ namespace Newtonsoft.Json
if (!TestType(schema, JsonSchemaType.String))
return;
ValidateInEnumAndNotDisallowed(schema);
ValidateNotDisallowed(schema);
string value = _reader.Value.ToString();
@@ -636,7 +709,7 @@ namespace Newtonsoft.Json
if (!TestType(schema, JsonSchemaType.Integer))
return;
ValidateInEnumAndNotDisallowed(schema);
ValidateNotDisallowed(schema);
long value = Convert.ToInt64(_reader.Value, CultureInfo.InvariantCulture);
@@ -668,8 +741,14 @@ namespace Newtonsoft.Json
foreach (JsonSchemaModel currentSchema in CurrentSchemas)
{
if (currentSchema != null && currentSchema.Items != null && currentSchema.Items.Count > 1 && _currentScope.ArrayItemCount >= currentSchema.Items.Count)
// if there is positional validation and the array index is past the number of item validation schemas and there is no additonal items then error
if (currentSchema != null
&& currentSchema.PositionalItemsValidation
&& !currentSchema.AllowAdditionalItems
&& (currentSchema.Items == null || _currentScope.ArrayItemCount - 1 >= currentSchema.Items.Count))
{
RaiseError("Index {0} has not been defined and the schema does not allow additional items.".FormatWith(CultureInfo.InvariantCulture, _currentScope.ArrayItemCount), currentSchema);
}
}
}
}
@@ -682,7 +761,7 @@ namespace Newtonsoft.Json
if (!TestType(schema, JsonSchemaType.Float))
return;
ValidateInEnumAndNotDisallowed(schema);
ValidateNotDisallowed(schema);
double value = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
@@ -702,8 +781,18 @@ namespace Newtonsoft.Json
RaiseError("Float {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema);
}
if (schema.DivisibleBy != null && !IsZero(value % schema.DivisibleBy.Value))
RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema);
if (schema.DivisibleBy != null)
{
double remainder = FloatingPointRemainder(value, schema.DivisibleBy.Value);
if (!IsZero(remainder))
RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema);
}
}
private static double FloatingPointRemainder(double dividend, double divisor)
{
return dividend - Math.Floor(dividend/divisor)*divisor;
}
private static bool IsZero(double value)
+16 -5
View File
@@ -394,10 +394,20 @@ namespace Newtonsoft.Json
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
@@ -410,10 +420,10 @@ namespace Newtonsoft.Json
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth);
WriteToken(reader, initialDepth, writeChildren);
}
internal void WriteToken(JsonReader reader, int initialDepth)
internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren)
{
do
{
@@ -499,6 +509,7 @@ namespace Newtonsoft.Json
while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
@@ -520,7 +531,7 @@ namespace Newtonsoft.Json
WriteValue(date);
}
private bool IsEndToken(JsonToken token)
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
@@ -533,7 +544,7 @@ namespace Newtonsoft.Json
}
}
private bool IsStartToken(JsonToken token)
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
+40
View File
@@ -30,6 +30,7 @@ using System.Dynamic;
using System.Linq.Expressions;
#endif
using System.IO;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
using System.Globalization;
@@ -1699,5 +1700,44 @@ namespace Newtonsoft.Json.Linq
{
return CloneToken();
}
public string Path
{
get
{
IList<JToken> ancestors = Ancestors().Reverse().ToList();
ancestors.Add(this);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ancestors.Count; i++)
{
JToken current = ancestors[i];
JToken next = (i + 1 < ancestors.Count) ? ancestors[i + 1] : null;
if (next != null)
{
switch (current.Type)
{
case JTokenType.Property:
JProperty property = (JProperty) current;
if (sb.Length > 0)
sb.Append(".");
sb.Append(property.Name);
break;
case JTokenType.Array:
case JTokenType.Constructor:
int index = ((IList<JToken>)current).IndexOf(next);
sb.Append("[" + index + "]");
break;
}
}
}
return sb.ToString();
}
}
}
}
+1 -1
View File
@@ -173,7 +173,7 @@ namespace Newtonsoft.Json.Linq
}
else
{
_value = value;
_value = value ?? new JValue((object)null);
}
}
@@ -31,6 +31,7 @@ namespace Newtonsoft.Json
{
/// <summary>
/// Specifies reference handling options for the <see cref="JsonSerializer"/>.
/// Note that references cannot be preserved when a value is set via a non-default constructor such as types that implement ISerializable.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="PreservingObjectReferencesOn" title="Preserve Object References" />
@@ -90,7 +90,7 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.11.15520")]
[assembly: AssemblyFileVersion("4.5.11.15631")]
#endif
[assembly: CLSCompliant(true)]
+35 -14
View File
@@ -126,6 +126,29 @@ namespace Newtonsoft.Json.Schema
/// <value>The <see cref="JsonSchema"/> of items.</value>
public IList<JsonSchema> Items { get; set; }
/// <summary>
/// Gets or sets a value indicating whether items in an array are validated using the <see cref="JsonSchema"/> instance at their array position from <see cref="JsonSchema.Items"/>.
/// </summary>
/// <value>
/// <c>true</c> if items are validated using their array position; otherwise, <c>false</c>.
/// </value>
public bool PositionalItemsValidation { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of additional items.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of additional items.</value>
public JsonSchema AdditionalItems { get; set; }
/// <summary>
/// Gets or sets a value indicating whether additional items are allowed.
/// </summary>
/// <value>
/// <c>true</c> if additional items are allowed; otherwise, <c>false</c>.
/// </value>
public bool AllowAdditionalItems { get; set; }
/// <summary>
/// Gets or sets whether the array items must be unique.
/// </summary>
public bool UniqueItems { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of properties.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of properties.</value>
@@ -153,21 +176,11 @@ namespace Newtonsoft.Json.Schema
/// <value>The required property if this property is present.</value>
public string Requires { get; set; }
/// <summary>
/// Gets or sets the identity.
/// </summary>
/// <value>The identity.</value>
public IList<string> Identity { get; set; }
/// <summary>
/// Gets or sets the a collection of valid enum values allowed.
/// </summary>
/// <value>A collection of valid enum values allowed.</value>
public IList<JToken> Enum { get; set; }
/// <summary>
/// Gets or sets a collection of options.
/// </summary>
/// <value>A collection of options.</value>
public IDictionary<JToken, string> Options { get; set; }
/// <summary>
/// Gets or sets disallowed types.
/// </summary>
/// <value>The disallow types.</value>
@@ -178,16 +191,18 @@ namespace Newtonsoft.Json.Schema
/// <value>The default value.</value>
public JToken Default { get; set; }
/// <summary>
/// Gets or sets the extend <see cref="JsonSchema"/>.
/// Gets or sets the collection of <see cref="JsonSchema"/> that this schema extends.
/// </summary>
/// <value>The extended <see cref="JsonSchema"/>.</value>
public JsonSchema Extends { get; set; }
/// <value>The collection of <see cref="JsonSchema"/> that this schema extends.</value>
public IList<JsonSchema> Extends { get; set; }
/// <summary>
/// Gets or sets the format.
/// </summary>
/// <value>The format.</value>
public string Format { get; set; }
public string Location { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
internal string InternalId
@@ -195,12 +210,18 @@ namespace Newtonsoft.Json.Schema
get { return _internalId; }
}
// if this is set then this schema instance is just a deferred reference
// and will be replaced when the schema reference is resolved
internal string DeferredReference { get; set; }
internal bool ReferencesResolved { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchema"/> class.
/// </summary>
public JsonSchema()
{
AllowAdditionalProperties = true;
AllowAdditionalItems = true;
}
/// <summary>
@@ -225,7 +246,7 @@ namespace Newtonsoft.Json.Schema
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
return builder.Parse(reader);
return builder.Read(reader);
}
/// <summary>
+298 -284
View File
@@ -38,16 +38,25 @@ namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaBuilder
{
private JsonReader _reader;
private readonly IList<JsonSchema> _stack;
private readonly JsonSchemaResolver _resolver;
private readonly IDictionary<string, JsonSchema> _documentSchemas;
private JsonSchema _currentSchema;
private JObject _rootSchema;
public JsonSchemaBuilder(JsonSchemaResolver resolver)
{
_stack = new List<JsonSchema>();
_documentSchemas = new Dictionary<string, JsonSchema>();
_resolver = resolver;
}
private void Push(JsonSchema value)
{
_currentSchema = value;
_stack.Add(value);
_resolver.LoadedSchemas.Add(value);
_documentSchemas.Add(value.Location, value);
}
private JsonSchema Pop()
@@ -64,355 +73,360 @@ namespace Newtonsoft.Json.Schema
get { return _currentSchema; }
}
public JsonSchemaBuilder(JsonSchemaResolver resolver)
internal JsonSchema Read(JsonReader reader)
{
_stack = new List<JsonSchema>();
_resolver = resolver;
JToken schemaToken = JToken.ReadFrom(reader);
_rootSchema = schemaToken as JObject;
JsonSchema schema = BuildSchema(schemaToken);
ResolveReferences(schema);
return schema;
}
internal JsonSchema Parse(JsonReader reader)
private string UnescapeReference(string reference)
{
_reader = reader;
if (reader.TokenType == JsonToken.None)
_reader.Read();
return BuildSchema();
return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~");
}
private JsonSchema BuildSchema()
private JsonSchema ResolveReferences(JsonSchema schema)
{
if (_reader.TokenType != JsonToken.StartObject)
throw JsonReaderException.Create(_reader, "Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
_reader.Read();
// empty schema object
if (_reader.TokenType == JsonToken.EndObject)
if (schema.DeferredReference != null)
{
Push(new JsonSchema());
return Pop();
}
string reference = schema.DeferredReference;
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
// schema reference
if (propertyName == JsonSchemaConstants.ReferencePropertyName)
{
string id = (string)_reader.Value;
bool locationReference = (reference.StartsWith("#", StringComparison.OrdinalIgnoreCase));
if (locationReference)
reference = UnescapeReference(reference);
// skip to the end of the current object
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
JsonSchema resolvedSchema = _resolver.GetSchema(reference);
if (resolvedSchema == null)
{
if (_reader.TokenType == JsonToken.StartObject)
throw JsonReaderException.Create(_reader, "Found StartObject within the schema reference with the Id '{0}'".FormatWith(CultureInfo.InvariantCulture, id));
if (locationReference)
{
string[] escapedParts = schema.DeferredReference.TrimStart('#').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken currentToken = _rootSchema;
foreach (string escapedPart in escapedParts)
{
string part = UnescapeReference(escapedPart);
if (currentToken.Type == JTokenType.Object)
{
currentToken = currentToken[part];
}
else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor)
{
int index;
if (int.TryParse(part, out index))
currentToken = currentToken[index];
else
currentToken = null;
}
if (currentToken == null)
break;
}
if (currentToken != null)
resolvedSchema = BuildSchema(currentToken);
}
if (resolvedSchema == null)
throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference));
}
JsonSchema referencedSchema = _resolver.GetSchema(id);
if (referencedSchema == null)
throw new JsonException("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
return referencedSchema;
schema = resolvedSchema;
}
// regular ol' schema object
Push(new JsonSchema());
if (schema.ReferencesResolved)
return schema;
ProcessSchemaProperty(propertyName);
schema.ReferencesResolved = true;
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
if (schema.Extends != null)
{
propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
ProcessSchemaProperty(propertyName);
for (int i = 0; i < schema.Extends.Count; i++)
{
schema.Extends[i] = ResolveReferences(schema.Extends[i]);
}
}
if (schema.Items != null)
{
for (int i = 0; i < schema.Items.Count; i++)
{
schema.Items[i] = ResolveReferences(schema.Items[i]);
}
}
if (schema.AdditionalItems != null)
schema.AdditionalItems = ResolveReferences(schema.AdditionalItems);
if (schema.PatternProperties != null)
{
foreach (KeyValuePair<string, JsonSchema> patternProperty in schema.PatternProperties.ToList())
{
schema.PatternProperties[patternProperty.Key] = ResolveReferences(patternProperty.Value);
}
}
if (schema.Properties != null)
{
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties.ToList())
{
schema.Properties[property.Key] = ResolveReferences(property.Value);
}
}
if (schema.AdditionalProperties != null)
schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties);
return schema;
}
private JsonSchema BuildSchema(JToken token)
{
JObject schemaObject = token as JObject;
if (schemaObject == null)
throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
JToken referenceToken;
if (schemaObject.TryGetValue(JsonSchemaConstants.ReferencePropertyName, out referenceToken))
{
JsonSchema deferredSchema = new JsonSchema();
deferredSchema.DeferredReference = (string)referenceToken;
return deferredSchema;
}
string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty);
if (!string.IsNullOrEmpty(location))
location = "/" + location;
location = "#" + location;
JsonSchema existingSchema;
if (_documentSchemas.TryGetValue(location, out existingSchema))
return existingSchema;
Push(new JsonSchema { Location = location });
ProcessSchemaProperties(schemaObject);
return Pop();
}
private void ProcessSchemaProperty(string propertyName)
private void ProcessSchemaProperties(JObject schemaObject)
{
switch (propertyName)
foreach (KeyValuePair<string, JToken> property in schemaObject)
{
case JsonSchemaConstants.TypePropertyName:
CurrentSchema.Type = ProcessType();
break;
case JsonSchemaConstants.IdPropertyName:
CurrentSchema.Id = (string) _reader.Value;
break;
case JsonSchemaConstants.TitlePropertyName:
CurrentSchema.Title = (string) _reader.Value;
break;
case JsonSchemaConstants.DescriptionPropertyName:
CurrentSchema.Description = (string)_reader.Value;
break;
case JsonSchemaConstants.PropertiesPropertyName:
ProcessProperties();
break;
case JsonSchemaConstants.ItemsPropertyName:
ProcessItems();
break;
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
ProcessAdditionalProperties();
break;
case JsonSchemaConstants.PatternPropertiesPropertyName:
ProcessPatternProperties();
break;
case JsonSchemaConstants.RequiredPropertyName:
CurrentSchema.Required = (bool)_reader.Value;
break;
case JsonSchemaConstants.RequiresPropertyName:
CurrentSchema.Requires = (string) _reader.Value;
break;
case JsonSchemaConstants.IdentityPropertyName:
ProcessIdentity();
break;
case JsonSchemaConstants.MinimumPropertyName:
CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.MaximumPropertyName:
CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
CurrentSchema.ExclusiveMinimum = (bool)_reader.Value;
break;
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
CurrentSchema.ExclusiveMaximum = (bool)_reader.Value;
break;
case JsonSchemaConstants.MaximumLengthPropertyName:
CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.MinimumLengthPropertyName:
CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.MaximumItemsPropertyName:
CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.MinimumItemsPropertyName:
CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.DivisibleByPropertyName:
CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
break;
case JsonSchemaConstants.DisallowPropertyName:
CurrentSchema.Disallow = ProcessType();
break;
case JsonSchemaConstants.DefaultPropertyName:
ProcessDefault();
break;
case JsonSchemaConstants.HiddenPropertyName:
CurrentSchema.Hidden = (bool) _reader.Value;
break;
case JsonSchemaConstants.ReadOnlyPropertyName:
CurrentSchema.ReadOnly = (bool) _reader.Value;
break;
case JsonSchemaConstants.FormatPropertyName:
CurrentSchema.Format = (string) _reader.Value;
break;
case JsonSchemaConstants.PatternPropertyName:
CurrentSchema.Pattern = (string) _reader.Value;
break;
case JsonSchemaConstants.OptionsPropertyName:
ProcessOptions();
break;
case JsonSchemaConstants.EnumPropertyName:
ProcessEnum();
break;
case JsonSchemaConstants.ExtendsPropertyName:
ProcessExtends();
break;
default:
_reader.Skip();
break;
switch (property.Key)
{
case JsonSchemaConstants.TypePropertyName:
CurrentSchema.Type = ProcessType(property.Value);
break;
case JsonSchemaConstants.IdPropertyName:
CurrentSchema.Id = (string)property.Value;
break;
case JsonSchemaConstants.TitlePropertyName:
CurrentSchema.Title = (string)property.Value;
break;
case JsonSchemaConstants.DescriptionPropertyName:
CurrentSchema.Description = (string)property.Value;
break;
case JsonSchemaConstants.PropertiesPropertyName:
CurrentSchema.Properties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.ItemsPropertyName:
ProcessItems(property.Value);
break;
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
ProcessAdditionalProperties(property.Value);
break;
case JsonSchemaConstants.AdditionalItemsPropertyName:
ProcessAdditionalItems(property.Value);
break;
case JsonSchemaConstants.PatternPropertiesPropertyName:
CurrentSchema.PatternProperties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.RequiredPropertyName:
CurrentSchema.Required = (bool)property.Value;
break;
case JsonSchemaConstants.RequiresPropertyName:
CurrentSchema.Requires = (string)property.Value;
break;
case JsonSchemaConstants.MinimumPropertyName:
CurrentSchema.Minimum = (double)property.Value;
break;
case JsonSchemaConstants.MaximumPropertyName:
CurrentSchema.Maximum = (double)property.Value;
break;
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
CurrentSchema.ExclusiveMinimum = (bool)property.Value;
break;
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
CurrentSchema.ExclusiveMaximum = (bool)property.Value;
break;
case JsonSchemaConstants.MaximumLengthPropertyName:
CurrentSchema.MaximumLength = (int)property.Value;
break;
case JsonSchemaConstants.MinimumLengthPropertyName:
CurrentSchema.MinimumLength = (int)property.Value;
break;
case JsonSchemaConstants.MaximumItemsPropertyName:
CurrentSchema.MaximumItems = (int)property.Value;
break;
case JsonSchemaConstants.MinimumItemsPropertyName:
CurrentSchema.MinimumItems = (int)property.Value;
break;
case JsonSchemaConstants.DivisibleByPropertyName:
CurrentSchema.DivisibleBy = (double)property.Value;
break;
case JsonSchemaConstants.DisallowPropertyName:
CurrentSchema.Disallow = ProcessType(property.Value);
break;
case JsonSchemaConstants.DefaultPropertyName:
CurrentSchema.Default = property.Value.DeepClone();
break;
case JsonSchemaConstants.HiddenPropertyName:
CurrentSchema.Hidden = (bool)property.Value;
break;
case JsonSchemaConstants.ReadOnlyPropertyName:
CurrentSchema.ReadOnly = (bool)property.Value;
break;
case JsonSchemaConstants.FormatPropertyName:
CurrentSchema.Format = (string)property.Value;
break;
case JsonSchemaConstants.PatternPropertyName:
CurrentSchema.Pattern = (string)property.Value;
break;
case JsonSchemaConstants.EnumPropertyName:
ProcessEnum(property.Value);
break;
case JsonSchemaConstants.ExtendsPropertyName:
ProcessExtends(property.Value);
break;
case JsonSchemaConstants.UniqueItemsPropertyName:
CurrentSchema.UniqueItems = (bool)property.Value;
break;
}
}
}
private void ProcessExtends()
private void ProcessExtends(JToken token)
{
CurrentSchema.Extends = BuildSchema();
IList<JsonSchema> schemas = new List<JsonSchema>();
if (token.Type == JTokenType.Array)
{
foreach (JToken schemaObject in token)
{
schemas.Add(BuildSchema(schemaObject));
}
}
else
{
JsonSchema schema = BuildSchema(token);
if (schema != null)
schemas.Add(schema);
}
if (schemas.Count > 0)
CurrentSchema.Extends = schemas;
}
private void ProcessEnum()
private void ProcessEnum(JToken token)
{
if (_reader.TokenType != JsonToken.StartArray)
throw JsonReaderException.Create(_reader, "Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
if (token.Type != JTokenType.Array)
throw JsonException.Create(token, token.Path, "Expected Array token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
CurrentSchema.Enum = new List<JToken>();
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
foreach (JToken enumValue in token)
{
JToken value = JToken.ReadFrom(_reader);
CurrentSchema.Enum.Add(value);
CurrentSchema.Enum.Add(enumValue.DeepClone());
}
}
private void ProcessOptions()
private void ProcessAdditionalProperties(JToken token)
{
CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer());
switch (_reader.TokenType)
{
case JsonToken.StartArray:
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{
if (_reader.TokenType != JsonToken.StartObject)
throw JsonReaderException.Create(_reader, "Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
string label = null;
JToken value = null;
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
switch (propertyName)
{
case JsonSchemaConstants.OptionValuePropertyName:
value = JToken.ReadFrom(_reader);
break;
case JsonSchemaConstants.OptionLabelPropertyName:
label = (string) _reader.Value;
break;
default:
throw JsonReaderException.Create(_reader, "Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
}
if (value == null)
throw new JsonException("No value specified for JSON schema option.");
if (CurrentSchema.Options.ContainsKey(value))
throw new JsonException("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
CurrentSchema.Options.Add(value, label);
}
break;
default:
throw JsonReaderException.Create(_reader, "Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
}
}
private void ProcessDefault()
{
CurrentSchema.Default = JToken.ReadFrom(_reader);
}
private void ProcessIdentity()
{
CurrentSchema.Identity = new List<string>();
switch (_reader.TokenType)
{
case JsonToken.String:
CurrentSchema.Identity.Add(_reader.Value.ToString());
break;
case JsonToken.StartArray:
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{
if (_reader.TokenType != JsonToken.String)
throw JsonReaderException.Create(_reader, "Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
CurrentSchema.Identity.Add(_reader.Value.ToString());
}
break;
default:
throw JsonReaderException.Create(_reader, "Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
}
}
private void ProcessAdditionalProperties()
{
if (_reader.TokenType == JsonToken.Boolean)
CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value;
if (token.Type == JTokenType.Boolean)
CurrentSchema.AllowAdditionalProperties = (bool)token;
else
CurrentSchema.AdditionalProperties = BuildSchema();
CurrentSchema.AdditionalProperties = BuildSchema(token);
}
private void ProcessPatternProperties()
private void ProcessAdditionalItems(JToken token)
{
Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>();
if (_reader.TokenType != JsonToken.StartObject)
throw JsonReaderException.Create(_reader, "Expected StartObject token.");
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
if (patternProperties.ContainsKey(propertyName))
throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
patternProperties.Add(propertyName, BuildSchema());
}
CurrentSchema.PatternProperties = patternProperties;
if (token.Type == JTokenType.Boolean)
CurrentSchema.AllowAdditionalItems = (bool)token;
else
CurrentSchema.AdditionalItems = BuildSchema(token);
}
private void ProcessItems()
{
CurrentSchema.Items = new List<JsonSchema>();
switch (_reader.TokenType)
{
case JsonToken.StartObject:
CurrentSchema.Items.Add(BuildSchema());
break;
case JsonToken.StartArray:
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{
CurrentSchema.Items.Add(BuildSchema());
}
break;
default:
throw JsonReaderException.Create(_reader, "Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
}
}
private void ProcessProperties()
private IDictionary<string, JsonSchema> ProcessProperties(JToken token)
{
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
if (_reader.TokenType != JsonToken.StartObject)
throw JsonReaderException.Create(_reader, "Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
if (token.Type != JTokenType.Object)
throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
foreach (JProperty propertyToken in token)
{
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
if (properties.ContainsKey(propertyToken.Name))
throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name));
if (properties.ContainsKey(propertyName))
throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
properties.Add(propertyName, BuildSchema());
properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value));
}
CurrentSchema.Properties = properties;
return properties;
}
private JsonSchemaType? ProcessType()
private void ProcessItems(JToken token)
{
switch (_reader.TokenType)
CurrentSchema.Items = new List<JsonSchema>();
switch (token.Type)
{
case JsonToken.String:
return MapType(_reader.Value.ToString());
case JsonToken.StartArray:
// ensure type is in blank state before ORing values
case JTokenType.Object:
CurrentSchema.Items.Add(BuildSchema(token));
CurrentSchema.PositionalItemsValidation = false;
break;
case JTokenType.Array:
CurrentSchema.PositionalItemsValidation = true;
foreach (JToken schemaToken in token)
{
CurrentSchema.Items.Add(BuildSchema(schemaToken));
}
break;
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
private JsonSchemaType? ProcessType(JToken token)
{
switch (token.Type)
{
case JTokenType.Array:
// ensure type is in blank state before ORing values
JsonSchemaType? type = JsonSchemaType.None;
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
foreach (JToken typeToken in token)
{
if (_reader.TokenType != JsonToken.String)
throw JsonReaderException.Create(_reader, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
if (typeToken.Type != JTokenType.String)
throw JsonException.Create(typeToken, typeToken.Path, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
type = type | MapType(_reader.Value.ToString());
type = type | MapType((string) typeToken);
}
return type;
case JTokenType.String:
return MapType((string)token);
default:
throw JsonReaderException.Create(_reader, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
throw JsonException.Create(token, token.Path, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
@@ -32,11 +32,11 @@ namespace Newtonsoft.Json.Schema
public const string TypePropertyName = "type";
public const string PropertiesPropertyName = "properties";
public const string ItemsPropertyName = "items";
public const string AdditionalItemsPropertyName = "additionalItems";
public const string RequiredPropertyName = "required";
public const string PatternPropertiesPropertyName = "patternProperties";
public const string AdditionalPropertiesPropertyName = "additionalProperties";
public const string RequiresPropertyName = "requires";
public const string IdentityPropertyName = "identity";
public const string MinimumPropertyName = "minimum";
public const string MaximumPropertyName = "maximum";
public const string ExclusiveMinimumPropertyName = "exclusiveMinimum";
@@ -47,7 +47,6 @@ namespace Newtonsoft.Json.Schema
public const string MaximumLengthPropertyName = "maxLength";
public const string MinimumLengthPropertyName = "minLength";
public const string EnumPropertyName = "enum";
public const string OptionsPropertyName = "options";
public const string ReadOnlyPropertyName = "readonly";
public const string TitlePropertyName = "title";
public const string DescriptionPropertyName = "description";
@@ -59,6 +58,7 @@ namespace Newtonsoft.Json.Schema
public const string DisallowPropertyName = "disallow";
public const string ExtendsPropertyName = "extends";
public const string IdPropertyName = "id";
public const string UniqueItemsPropertyName = "uniqueItems";
public const string OptionValuePropertyName = "value";
public const string OptionLabelPropertyName = "label";
@@ -295,7 +295,6 @@ namespace Newtonsoft.Json.Schema
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
@@ -303,7 +302,6 @@ namespace Newtonsoft.Json.Schema
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
break;
@@ -47,7 +47,11 @@ namespace Newtonsoft.Json.Schema
public IDictionary<string, JsonSchemaModel> Properties { get; set; }
public IDictionary<string, JsonSchemaModel> PatternProperties { get; set; }
public JsonSchemaModel AdditionalProperties { get; set; }
public JsonSchemaModel AdditionalItems { get; set; }
public bool PositionalItemsValidation { get; set; }
public bool AllowAdditionalProperties { get; set; }
public bool AllowAdditionalItems { get; set; }
public bool UniqueItems { get; set; }
public IList<JToken> Enum { get; set; }
public JsonSchemaType Disallow { get; set; }
@@ -55,6 +59,7 @@ namespace Newtonsoft.Json.Schema
{
Type = JsonSchemaType.Any;
AllowAdditionalProperties = true;
AllowAdditionalItems = true;
Required = false;
}
@@ -89,13 +94,16 @@ namespace Newtonsoft.Json.Schema
model.MinimumItems = MathUtils.Max(model.MinimumItems, schema.MinimumItems);
model.MaximumItems = MathUtils.Min(model.MaximumItems, schema.MaximumItems);
model.PositionalItemsValidation = model.PositionalItemsValidation || schema.PositionalItemsValidation;
model.AllowAdditionalProperties = model.AllowAdditionalProperties && schema.AllowAdditionalProperties;
model.AllowAdditionalItems = model.AllowAdditionalItems && schema.AllowAdditionalItems;
model.UniqueItems = model.UniqueItems || schema.UniqueItems;
if (schema.Enum != null)
{
if (model.Enum == null)
model.Enum = new List<JToken>();
model.Enum.AddRangeDistinct(schema.Enum, new JTokenEqualityComparer());
model.Enum.AddRangeDistinct(schema.Enum, JToken.EqualityComparer);
}
model.Disallow = model.Disallow | (schema.Disallow ?? JsonSchemaType.None);
@@ -85,11 +85,19 @@ namespace Newtonsoft.Json.Schema
}
}
if (schema.AdditionalItems != null)
AddAdditionalItems(currentNode, schema.AdditionalItems);
if (schema.AdditionalProperties != null)
AddAdditionalProperties(currentNode, schema.AdditionalProperties);
if (schema.Extends != null)
currentNode = AddSchema(currentNode, schema.Extends);
{
foreach (JsonSchema jsonSchema in schema.Extends)
{
currentNode = AddSchema(currentNode, jsonSchema);
}
}
return currentNode;
}
@@ -136,6 +144,11 @@ namespace Newtonsoft.Json.Schema
parentNode.AdditionalProperties = AddSchema(parentNode.AdditionalProperties, schema);
}
public void AddAdditionalItems(JsonSchemaNode parentNode, JsonSchema schema)
{
parentNode.AdditionalItems = AddSchema(parentNode.AdditionalItems, schema);
}
private JsonSchemaModel BuildNodeModel(JsonSchemaNode node)
{
JsonSchemaModel model;
@@ -168,6 +181,8 @@ namespace Newtonsoft.Json.Schema
}
if (node.AdditionalProperties != null)
model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties);
if (node.AdditionalItems != null)
model.AdditionalItems = BuildNodeModel(node.AdditionalItems);
return model;
}
@@ -42,6 +42,7 @@ namespace Newtonsoft.Json.Schema
public Dictionary<string, JsonSchemaNode> PatternProperties { get; private set; }
public List<JsonSchemaNode> Items { get; private set; }
public JsonSchemaNode AdditionalProperties { get; set; }
public JsonSchemaNode AdditionalItems { get; set; }
public JsonSchemaNode(JsonSchema schema)
{
@@ -60,6 +61,7 @@ namespace Newtonsoft.Json.Schema
PatternProperties = new Dictionary<string, JsonSchemaNode>(source.PatternProperties);
Items = new List<JsonSchemaNode>(source.Items);
AdditionalProperties = source.AdditionalProperties;
AdditionalItems = source.AdditionalItems;
Id = GetId(Schemas);
}
@@ -23,6 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
@@ -52,13 +53,17 @@ namespace Newtonsoft.Json.Schema
}
/// <summary>
/// Gets a <see cref="JsonSchema"/> for the specified id.
/// Gets a <see cref="JsonSchema"/> for the specified reference.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>A <see cref="JsonSchema"/> for the specified id.</returns>
public virtual JsonSchema GetSchema(string id)
/// <param name="reference">The id.</param>
/// <returns>A <see cref="JsonSchema"/> for the specified reference.</returns>
public virtual JsonSchema GetSchema(string reference)
{
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => s.Id == id);
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Id, reference, StringComparison.Ordinal));
if (schema == null)
schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Location, reference, StringComparison.Ordinal));
return schema;
}
}
+43 -25
View File
@@ -91,6 +91,19 @@ namespace Newtonsoft.Json.Schema
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
if (!schema.AllowAdditionalItems)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
_writer.WriteValue(schema.AllowAdditionalItems);
}
else
{
if (schema.AdditionalItems != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
ReferenceOrWriteSchema(schema.AdditionalItems);
}
}
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties);
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties);
WriteItems(schema);
@@ -120,30 +133,24 @@ namespace Newtonsoft.Json.Schema
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
schema.Default.WriteTo(_writer);
}
if (schema.Options != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName);
_writer.WriteStartArray();
foreach (KeyValuePair<JToken, string> option in schema.Options)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
option.Key.WriteTo(_writer);
if (option.Value != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionLabelPropertyName);
_writer.WriteValue(option.Value);
}
_writer.WriteEndObject();
}
_writer.WriteEndArray();
}
if (schema.Disallow != null)
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
if (schema.Extends != null)
if (schema.Extends != null && schema.Extends.Count > 0)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
ReferenceOrWriteSchema(schema.Extends);
if (schema.Extends.Count == 1)
{
ReferenceOrWriteSchema(schema.Extends[0]);
}
else
{
_writer.WriteStartArray();
foreach (JsonSchema jsonSchema in schema.Extends)
{
ReferenceOrWriteSchema(jsonSchema);
}
_writer.WriteEndArray();
}
}
_writer.WriteEndObject();
}
@@ -165,21 +172,32 @@ namespace Newtonsoft.Json.Schema
private void WriteItems(JsonSchema schema)
{
if (CollectionUtils.IsNullOrEmpty(schema.Items))
if (schema.Items == null && !schema.PositionalItemsValidation)
return;
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (schema.Items.Count == 1)
if (!schema.PositionalItemsValidation)
{
ReferenceOrWriteSchema(schema.Items[0]);
if (schema.Items != null && schema.Items.Count > 0)
{
ReferenceOrWriteSchema(schema.Items[0]);
}
else
{
_writer.WriteStartObject();
_writer.WriteEndObject();
}
return;
}
_writer.WriteStartArray();
foreach (JsonSchema itemSchema in schema.Items)
if (schema.Items != null)
{
ReferenceOrWriteSchema(itemSchema);
foreach (JsonSchema itemSchema in schema.Items)
{
ReferenceOrWriteSchema(itemSchema);
}
}
_writer.WriteEndArray();
}
@@ -213,7 +213,7 @@ namespace Newtonsoft.Json.Serialization
writer.WriteStartObject();
if (reader.TokenType == JsonToken.PropertyName)
writer.WriteToken(reader, reader.Depth - 1);
writer.WriteToken(reader, reader.Depth - 1, true);
else
writer.WriteEndObject();