-Added JSON Schema implementation

-Move test serialization objects to TestObjects namespace
-Fixed JsonConvert to always write a floating point number with a decimal place
-Changed Type values to serialize and deserialize to type name string
-Fixed JsonWriter to allow objects and arrays to be written in a constructor
-Added JsonContainerAttribute with Id, Title and Description members. JsonObject and JsonArray inherit from this attribute
-Added JsonArrayAttribute. Has flag to control whether array can contain null items.
-Added IsRequired to JsonProperty
-Replaced protected method GetSerializableMembers with GetMemberMappings on JsonSerializer
-Fixed QuoteChar not getting set when parsing property name
-Added Load(JsonReader) to JProperty, JConstructor
-Fixed error when populating JProperty with content from collection
-Added the ability for JsonTokenWriter to write individual values as well as arrays and objects
-Added CreateReader to JToken
-Added FromObject to JToken
-Added ReadFrom to JToken
This commit is contained in:
JamesNK
2009-01-02 05:29:31 +00:00
parent f95868233e
commit 0319263756
113 changed files with 8324 additions and 741 deletions
+3
View File
@@ -87,6 +87,9 @@
<h5>NullValueHandling</h5>
<p>Controls how null values are handled during serialization and deserialization.
Include or ignore.</p>
<h5>DefaultValueHandling</h5>
<p>Controls whether a value will be written to JSON or not if it matches the value specified in
the member's DefaultValueAttribute. Include or ignore.</p>
<h5>ObjectCreationHandling</h5>
<p>Controls how objects are created during deserialization. Auto, reuse, replace.</p>
<h5>Converters</h5>
@@ -27,6 +27,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
@@ -27,6 +27,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Converters;
@@ -274,5 +274,22 @@ now brown cow?", '"', true);
object u = JsonConvert.DeserializeObject<object>("undefined");
Assert.AreEqual(null, u);
}
[Test]
public void FloatToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(double.PositiveInfinity));
Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(double.NegativeInfinity));
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(double.NaN));
}
}
}
+63 -483
View File
@@ -39,183 +39,10 @@ using Newtonsoft.Json.Converters;
#if !PocketPC
using System.Runtime.Serialization.Json;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.ComponentModel;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests
{
public class Product
{
public string Name;
public DateTime Expiry = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public decimal Price;
public string[] Sizes;
public override bool Equals(object obj)
{
if (obj is Product)
{
Product p = (Product)obj;
return (p.Name == Name && p.Expiry == Expiry && p.Price == Price);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return (Name ?? string.Empty).GetHashCode();
}
}
public class ProductCollection : List<Product>
{
}
public class ProductShort
{
public string Name;
public DateTime Expiry;
//public decimal Price;
public string[] Sizes;
}
public class Store
{
public StoreColor Color = StoreColor.Yellow;
public DateTimeOffset Establised = new DateTimeOffset(2010, 1, 22, 1, 1, 1, TimeSpan.Zero);
public double Width = 1.1;
public int Employees = 999;
public int[] RoomsPerFloor = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public bool Open = false;
public char Symbol = '@';
public List<string> Mottos = new List<string>();
public decimal Cost = 100980.1M;
public string Escape = "\r\n\t\f\b?{\\r\\n\"\'";
public List<Product> product = new List<Product>();
public Store()
{
Mottos.Add("Hello World");
Mottos.Add("鲣�能\\'{new Date(12345);}[222]_礍渤~");
Mottos.Add(null);
Mottos.Add(" ");
Product rocket = new Product();
rocket.Name = "Rocket";
rocket.Expiry = new DateTime(2000, 2, 2, 23, 1, 30, DateTimeKind.Utc);
Product alien = new Product();
alien.Name = "Alien";
product.Add(rocket);
product.Add(alien);
}
}
public enum StoreColor
{
Black,
Red,
Yellow,
White
}
public class ClassWithGuid
{
public Guid GuidField;
}
public class ClassWithArray
{
private readonly IList<long> bar;
private string foo;
public ClassWithArray()
{
bar = new List<Int64>() { int.MaxValue };
}
[JsonProperty("foo")]
public string Foo
{
get { return foo; }
set { foo = value; }
}
[JsonProperty(PropertyName = "bar")]
public IList<long> Bar
{
get { return bar; }
}
}
[JsonObject]
public class ConverableMembers
{
public string String = "string";
public int Int32 = int.MaxValue;
public uint UInt32 = uint.MaxValue;
public byte Byte = byte.MaxValue;
public sbyte SByte = sbyte.MaxValue;
public short Short = short.MaxValue;
public ushort UShort = ushort.MaxValue;
public long Long = long.MaxValue;
public ulong ULong = long.MaxValue;
public double Double = double.MaxValue;
public float Float = float.MaxValue;
public DBNull DBNull = DBNull.Value;
public bool Bool = true;
public char Char = '\0';
}
[JsonObject(MemberSerialization.OptIn)]
public class JsonIgnoreAttributeOnClassTestClass
{
private int _property = 21;
private int _ignoredProperty = 12;
[JsonProperty("TheField")]
public int Field;
[JsonProperty]
public int Property
{
get { return _property; }
}
public int IgnoredField;
[JsonProperty]
[JsonIgnore] // JsonIgnore should take priority
public int IgnoredProperty
{
get { return _ignoredProperty; }
}
}
[JsonObject(MemberSerialization.OptIn)]
public class Person
{
// "John Smith"
[JsonProperty]
public string Name { get; set; }
// "2000-12-15T22:11:03"
[JsonProperty]
//[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime BirthDate { get; set; }
// new Date(976918263055)
[JsonProperty]
//[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime LastModified { get; set; }
// not serialized
public string Department { get; set; }
}
public class JsonSerializerTest : TestFixtureBase
{
[Test]
@@ -314,13 +141,6 @@ namespace Newtonsoft.Json.Tests
Console.WriteLine(jsonText);
}
public class MethodExecutorObject
{
public string serverClassName;
public object[] serverMethodParams;
public string clientGetResultFunction;
}
[Test]
public void TestMethodExecutorObject()
{
@@ -351,12 +171,6 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual("Orange", p["Name"].ToString());
}
public class TypedSubHashtable
{
public string Name;
public Hashtable Hash;
}
[Test]
public void TypedHashtableDeserialization()
{
@@ -371,16 +185,6 @@ namespace Newtonsoft.Json.Tests
}
#endif
public class GetOnlyPropertyClass
{
public string Field = "Field";
public string GetOnlyProperty
{
get { return "GetOnlyProperty"; }
}
}
[Test]
public void SerializeDeserializeGetOnlyProperty()
{
@@ -392,16 +196,6 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual(c.GetOnlyProperty, "GetOnlyProperty");
}
public class SetOnlyPropertyClass
{
public string Field = "Field";
public string SetOnlyProperty
{
set { }
}
}
[Test]
public void SerializeDeserializeSetOnlyProperty()
{
@@ -412,30 +206,6 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual(c.Field, "Field");
}
public class JsonIgnoreAttributeTestClass
{
private int _property = 21;
private int _ignoredProperty = 12;
public int Field;
public int Property
{
get { return _property; }
}
[JsonIgnore]
public int IgnoredField;
[JsonIgnore]
public int IgnoredProperty
{
get { return _ignoredProperty; }
}
[JsonIgnore]
public Product IgnoredObject = new Product();
}
[Test]
public void JsonIgnoreAttributeTest()
{
@@ -594,39 +364,13 @@ keyword such as type of business.""
Assert.AreEqual(test.SweetCakesCount, test2.SweetCakesCount);
}
public class BadJsonPropertyClass
{
[JsonProperty("pie")]
public string Pie = "Yum";
public string pie = "PieChart!";
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on Newtonsoft.Json.Tests.JsonSerializerTest+BadJsonPropertyClass. Use the JsonPropertyAttribute to specify another name.")]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass. Use the JsonPropertyAttribute to specify another name.")]
public void BadJsonPropertyClassSerialize()
{
JsonConvert.SerializeObject(new BadJsonPropertyClass());
}
public class Article
{
public string Name;
public Article()
{
}
public Article(string name)
{
Name = name;
}
}
public class ArticleCollection : List<Article>
{
}
[Test]
public void InheritedListSerialize()
{
@@ -657,26 +401,6 @@ keyword such as type of business.""
CollectionAssert.AreEqual(r1, r2);
}
public class Person
{
private Guid _internalId;
private string _firstName;
[JsonIgnore]
public Guid InternalId
{
get { return _internalId; }
set { _internalId = value; }
}
[JsonProperty("first_name")]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not find member 'Price' on object of type 'RuntimeType'")]
public void MissingMemberDeserialize()
@@ -1042,28 +766,6 @@ keyword such as type of business.""
}
#endif
public class Name
{
public string personsName;
public List<PhoneNumber> pNumbers = new List<PhoneNumber>();
public Name(string personsName)
{
this.personsName = personsName;
}
}
public class PhoneNumber
{
public string phoneNumber;
public PhoneNumber(string phoneNumber)
{
this.phoneNumber = phoneNumber;
}
}
[Test]
public void SerializeMemberGenericList()
{
@@ -1085,20 +787,6 @@ keyword such as type of business.""
Assert.AreEqual(0, newName.pNumbers.Count);
}
public class ConstructorCaseSensitivityClass
{
public string param1 { get; set; }
public string Param1 { get; set; }
public string Param2 { get; set; }
public ConstructorCaseSensitivityClass(string param1, string Param1, string param2)
{
this.param1 = param1;
this.Param1 = Param1;
this.Param2 = param2;
}
}
[Test]
public void ConstructorCaseSensitivity()
{
@@ -1113,72 +801,6 @@ keyword such as type of business.""
Assert.AreEqual("Param2", deserialized.Param2);
}
public class MemberConverterPrecedenceClassConverter : ConverterPrecedenceClassConverter
{
public override string ConverterType
{
get { return "Member"; }
}
}
public class ClassConverterPrecedenceClassConverter : ConverterPrecedenceClassConverter
{
public override string ConverterType
{
get { return "Class"; }
}
}
public class ArgumentConverterPrecedenceClassConverter : ConverterPrecedenceClassConverter
{
public override string ConverterType
{
get { return "Argument"; }
}
}
public abstract class ConverterPrecedenceClassConverter : JsonConverter
{
public abstract string ConverterType { get; }
public override void WriteJson(JsonWriter writer, object value)
{
ConverterPrecedenceClass c = (ConverterPrecedenceClass)value;
JToken j = new JArray(ConverterType, c.TestValue);
j.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType)
{
JToken j = JArray.Load(reader);
string converter = (string)j[0];
if (converter != ConverterType)
throw new Exception("Serialize converter {0} and deserialize converter {1} do not match.".FormatWith(CultureInfo.InvariantCulture, converter, ConverterType));
string testValue = (string)j[1];
return new ConverterPrecedenceClass(testValue);
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ConverterPrecedenceClass));
}
}
[JsonConverter(typeof(ClassConverterPrecedenceClassConverter))]
public class ConverterPrecedenceClass
{
public string TestValue { get; set; }
public ConverterPrecedenceClass(string testValue)
{
TestValue = testValue;
}
}
[Test]
public void SerializerShouldUseClassConverter()
{
@@ -1205,13 +827,6 @@ keyword such as type of business.""
Assert.AreEqual("!Test!", c2.TestValue);
}
public class MemberConverterClass
{
public DateTime DefaultConverter { get; set; }
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime MemberConverter { get; set; }
}
[Test]
public void SerializerShouldUseMemberConverter()
{
@@ -1242,13 +857,6 @@ keyword such as type of business.""
Assert.AreEqual(testDate, m2.MemberConverter);
}
public class ClassAndMemberConverterClass
{
public ConverterPrecedenceClass DefaultConverter { get; set; }
[JsonConverter(typeof(MemberConverterPrecedenceClassConverter))]
public ConverterPrecedenceClass MemberConverter { get; set; }
}
[Test]
public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
{
@@ -1265,29 +873,14 @@ keyword such as type of business.""
Assert.AreEqual("MemberConverterValue", c2.MemberConverter.TestValue);
}
[JsonConverter(typeof(IsoDateTimeConverter))]
public class IncompatibleJsonAttributeClass
{
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.JsonSerializerTest+IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.")]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JsonConverter IsoDateTimeConverter on Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass is not compatible with member type IncompatibleJsonAttributeClass.")]
public void IncompatibleJsonAttributeShouldThrow()
{
IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
JsonConvert.SerializeObject(c);
}
public abstract class AbstractGenericBase<TKey>
{
public abstract TKey Id { get; set; }
}
public class GenericImpl : AbstractGenericBase<int>
{
public override int Id { get; set; }
}
[Test]
public void GenericAbstractProperty()
{
@@ -1295,15 +888,6 @@ keyword such as type of business.""
Assert.AreEqual(@"{""Id"":0}", json);
}
public class DefaultValueAttributeTestClass
{
[DefaultValue("TestProperty1Value")]
public string TestProperty1 { get; set; }
[DefaultValue(21)]
public int TestField1;
}
[Test]
public void DefaultValueAttributeTest()
{
@@ -1324,16 +908,6 @@ keyword such as type of business.""
Assert.AreEqual(@"{}", json);
}
public class Invoice
{
public string Company { get; set; }
public decimal Amount { get; set; }
[DefaultValue(false)]
public bool Paid { get; set; }
[DefaultValue(null)]
public DateTime? PaidDate { get; set; }
}
[Test]
public void SerializeInvoice()
{
@@ -1369,41 +943,6 @@ keyword such as type of business.""
Assert.AreEqual("1", json);
}
public class PersonRaw
{
private Guid _internalId;
private string _firstName;
private string _lastName;
private JsonRaw _rawContent;
[JsonIgnore]
public Guid InternalId
{
get { return _internalId; }
set { _internalId = value; }
}
[JsonProperty("first_name")]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public JsonRaw RawContent
{
get { return _rawContent; }
set { _rawContent = value; }
}
[JsonProperty("last_name")]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
[Test]
public void SerializeJsonRaw()
{
@@ -1432,21 +971,11 @@ keyword such as type of business.""
Assert.AreEqual("LastNameValue", personRaw.LastName);
}
public class UserNullablle
{
public Guid Id;
public string FName;
public string LName;
public int RoleId;
public int? NullableRoleId;
public int? NullRoleId;
public bool? Active;
}
[Test]
public void DeserializeNullableMember()
{
UserNullablle userNullablle = new UserNullablle
UserNullable userNullablle = new UserNullable
{
Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"),
FName = "FirstValue",
@@ -1461,7 +990,7 @@ keyword such as type of business.""
Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json);
UserNullablle userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullablle>(json);
UserNullable userNullablleDeserialized = JsonConvert.DeserializeObject<UserNullable>(json);
Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id);
Assert.AreEqual("FirstValue", userNullablleDeserialized.FName);
@@ -1472,13 +1001,6 @@ keyword such as type of business.""
Assert.AreEqual(true, userNullablleDeserialized.Active);
}
public class MyClass
{
public int PreProperty { get; set; }
//public DateTime DateProperty { get; set; }
public int PostProperty { get; set; }
}
[Test]
public void MissingMemberIgnoreComplexValue()
{
@@ -1492,5 +1014,63 @@ keyword such as type of business.""
Assert.AreEqual(1, myClass.PreProperty);
Assert.AreEqual(2, myClass.PostProperty);
}
[Test]
public void DeserializeInt64ToNullableDouble()
{
string json = @"{""Height"":1}";
DoubleClass c = JsonConvert.DeserializeObject<DoubleClass>(json);
Assert.AreEqual(1, c.Height);
}
[Test]
public void SerializeTypeProperty()
{
TypeClass typeClass = new TypeClass {TypeProperty = typeof (bool)};
string json = JsonConvert.SerializeObject(typeClass);
Assert.AreEqual(@"{""TypeProperty"":""System.Boolean""}", json);
TypeClass typeClass2 = JsonConvert.DeserializeObject<TypeClass>(json);
Assert.AreEqual(typeof(bool), typeClass2.TypeProperty);
}
[Test]
public void RequiredMembersClass()
{
RequiredMembersClass c = new RequiredMembersClass()
{
BirthDate = new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc),
FirstName = "Bob",
LastName = "Smith",
MiddleName = "Cosmo"
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"{
""FirstName"": ""Bob"",
""MiddleName"": ""Cosmo"",
""LastName"": ""Smith"",
""BirthDate"": ""\/Date(977309755000)\/""
}", json);
RequiredMembersClass c2 = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
Assert.AreEqual("Bob", c2.FirstName);
Assert.AreEqual(new DateTime(2000, 12, 20, 10, 55, 55, DateTimeKind.Utc), c2.BirthDate);
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON.")]
public void RequiredMembersClassMissingRequiredProperty()
{
string json = @"{
""FirstName"": ""Bob""
}";
JsonConvert.DeserializeObject<RequiredMembersClass>(json);
}
}
}
@@ -348,5 +348,81 @@ namespace Newtonsoft.Json.Tests
reader.Read();
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
}
[Test]
public void ReadFloatingPointNumber()
{
string json =
@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]";
using (JsonReader jsonReader = new JsonTextReader(new StringReader(json)))
{
jsonReader.Read();
Assert.AreEqual(JsonToken.StartArray, jsonReader.TokenType);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(0.0, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(0.0, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(0.1, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(1.0, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(1.000001, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(1E-06, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(4.94065645841247E-324, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.PositiveInfinity, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.NegativeInfinity, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.NaN, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.MaxValue, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.MinValue, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.PositiveInfinity, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.NegativeInfinity, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.Float, jsonReader.TokenType);
Assert.AreEqual(double.NaN, jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.EndArray, jsonReader.TokenType);
}
}
}
}
@@ -410,5 +410,61 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString());
}
[Test]
public void WriteObjectNestedInConstructor()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("con");
jsonWriter.WriteStartConstructor("Ext.data.JsonStore");
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("aa");
jsonWriter.WriteValue("aa");
jsonWriter.WriteEndObject();
jsonWriter.WriteEndConstructor();
jsonWriter.WriteEndObject();
}
Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString());
}
[Test]
public void WriteFloatingPointNumber()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteValue(0f);
jsonWriter.WriteValue(0.1);
jsonWriter.WriteValue(1.0);
jsonWriter.WriteValue(1.000001);
jsonWriter.WriteValue(0.000001);
jsonWriter.WriteValue(double.Epsilon);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.MaxValue);
jsonWriter.WriteValue(double.MinValue);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteEndArray();
}
Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString());
}
}
}
@@ -39,7 +39,7 @@ namespace Newtonsoft.Json.Tests
[Test]
public void ValueFormatting()
{
JContainer root;
JToken root;
using (JsonTokenWriter jsonWriter = new JsonTokenWriter())
{
jsonWriter.WriteStartArray();
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System.IO;
namespace Newtonsoft.Json.Tests.Linq
{
public class JConstructorTests : TestFixtureBase
{
[Test]
public void Load()
{
JsonReader reader = new JsonTextReader(new StringReader("new Date(123)"));
reader.Read();
JConstructor constructor = JConstructor.Load(reader);
Assert.AreEqual("Date", constructor.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(123), constructor.Values().ElementAt(0)));
}
[Test]
public void CreateWithMultiValue()
{
JConstructor constructor = new JConstructor("Test", new List<int> { 1, 2, 3 });
Assert.AreEqual("Test", constructor.Name);
Assert.AreEqual(3, constructor.Children().Count());
Assert.AreEqual(1, (int)constructor.Children().ElementAt(0));
Assert.AreEqual(2, (int)constructor.Children().ElementAt(1));
Assert.AreEqual(3, (int)constructor.Children().ElementAt(2));
}
}
}
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
@@ -235,7 +236,7 @@ Parameter name: arrayIndex")]
[Test]
public void FromObjectRaw()
{
JsonSerializerTest.PersonRaw raw = new JsonSerializerTest.PersonRaw
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JsonRaw("[1,2,3,4,5]"),
@@ -253,7 +254,7 @@ Parameter name: arrayIndex")]
[Test]
public void JsonTokenReader()
{
JsonSerializerTest.PersonRaw raw = new JsonSerializerTest.PersonRaw
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JsonRaw("[1,2,3,4,5]"),
@@ -294,7 +295,7 @@ Parameter name: arrayIndex")]
[Test]
public void DeserializeFromRaw()
{
JsonSerializerTest.PersonRaw raw = new JsonSerializerTest.PersonRaw
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JsonRaw("[1,2,3,4,5]"),
@@ -305,7 +306,7 @@ Parameter name: arrayIndex")]
JsonReader reader = new JsonTokenReader(o);
JsonSerializer serializer = new JsonSerializer();
raw = (JsonSerializerTest.PersonRaw)serializer.Deserialize(reader, typeof(JsonSerializerTest.PersonRaw));
raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
Assert.AreEqual("FirstNameValue", raw.FirstName);
Assert.AreEqual("LastNameValue", raw.LastName);
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System.IO;
namespace Newtonsoft.Json.Tests.Linq
{
public class JPropertyTests : TestFixtureBase
{
[Test]
public void Load()
{
JsonReader reader = new JsonTextReader(new StringReader("{'propertyname':['value1']}"));
reader.Read();
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
reader.Read();
JProperty property = JProperty.Load(reader);
Assert.AreEqual("propertyname", property.Name);
Assert.IsTrue(JToken.DeepEquals(JArray.Parse("['value1']"), property.Value));
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
reader = new JsonTextReader(new StringReader("{'propertyname':null}"));
reader.Read();
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
reader.Read();
property = JProperty.Load(reader);
Assert.AreEqual("propertyname", property.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(null, JsonTokenType.Null), property.Value));
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
}
[Test]
public void MultiContentConstructor()
{
JProperty p = new JProperty("error", new List<string> { "one", "two" });
JArray a = (JArray) p.Value;
Assert.AreEqual(a.Count, 2);
Assert.AreEqual("one", (string)a[0]);
Assert.AreEqual("two", (string)a[1]);
}
}
}
@@ -29,11 +29,47 @@ using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.IO;
namespace Newtonsoft.Json.Tests.Linq
{
public class JTokenTests : TestFixtureBase
{
[Test]
public void ReadFrom()
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]")));
Assert.AreEqual(1, (int)a[0]);
Assert.AreEqual(2, (int)a[1]);
Assert.AreEqual(3, (int)a[2]);
JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}"));
reader.Read();
reader.Read();
JProperty p = (JProperty)JToken.ReadFrom(reader);
Assert.AreEqual("pie", p.Name);
Assert.AreEqual(true, (bool)p.Value);
JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)")));
Assert.AreEqual("Date", c.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0)));
JValue v;
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue""")));
Assert.AreEqual("stringvalue", (string)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1")));
Assert.AreEqual(1, (int)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1")));
Assert.AreEqual(1.1, (double)v);
}
[Test]
public void Parent()
{
@@ -32,6 +32,7 @@ using Newtonsoft.Json.Linq;
using System.Xml;
using System.IO;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Linq
{
@@ -351,13 +352,13 @@ keyword such as type of business.""
[
""1"",
2,
3,
3.0,
""\/Date(-62030076711000)\/""
],
new ConstructorName(
""param1"",
2,
3
3.0
)
]", a.ToString());
}
@@ -58,12 +58,59 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="Converters\XmlNodeConverterTest.cs" />
<Compile Include="DateTimeTestClass.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
<Compile Include="TestObjects\CircularReferenceClass.cs" />
<Compile Include="TestObjects\ClassAndMemberConverterClass.cs" />
<Compile Include="TestObjects\ClassConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\ConstructorCaseSensitivityClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
<Compile Include="TestObjects\Invoice.cs" />
<Compile Include="TestObjects\JsonIgnoreAttributeTestClass.cs" />
<Compile Include="TestObjects\MemberConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\MethodExecutorObject.cs" />
<Compile Include="TestObjects\MyClass.cs" />
<Compile Include="TestObjects\Name.cs" />
<Compile Include="TestObjects\PersonRaw.cs" />
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
<Compile Include="TestObjects\ArticleCollection.cs" />
<Compile Include="TestObjects\ClassWithArray.cs" />
<Compile Include="TestObjects\ClassWithGuid.cs" />
<Compile Include="TestObjects\ConverableMembers.cs" />
<Compile Include="TestObjects\JsonIgnoreAttributeOnClassTestClass.cs" />
<Compile Include="Linq\JConstructorTests.cs" />
<Compile Include="Linq\JPropertyTests.cs" />
<Compile Include="TestObjects\MemberConverterClass.cs" />
<Compile Include="TestObjects\Product.cs" />
<Compile Include="TestObjects\ProductCollection.cs" />
<Compile Include="TestObjects\ProductShort.cs" />
<Compile Include="TestObjects\Store.cs" />
<Compile Include="TestObjects\StoreColor.cs" />
<Compile Include="TestObjects\Person.cs" />
<Compile Include="Schema\JsonSchemaBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaGeneratorTests.cs" />
<Compile Include="Schema\JsonSchemaTests.cs" />
<Compile Include="JsonRawTests.cs" />
<Compile Include="NullableDateTimeTestClass.cs" />
<Compile Include="TestObjects\DateTimeTestClass.cs" />
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="JsonTextReaderTest.cs" />
<Compile Include="JsonTextWriterTest.cs" />
@@ -75,11 +122,14 @@
<Compile Include="Linq\JTokenTests.cs" />
<Compile Include="Linq\JValueTests.cs" />
<Compile Include="Linq\LinqToJsonTest.cs" />
<Compile Include="NullableDateTimeTestClass.cs" />
<Compile Include="PerformanceTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SilverlightTests.cs" />
<Compile Include="TestFixtureBase.cs" />
<Compile Include="Converters\XmlNodeConverterTest.cs" />
<Compile Include="TestObjects\TypeClass.cs" />
<Compile Include="TestObjects\TypedSubHashtable.cs" />
<Compile Include="TestObjects\UserNullable.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.Compact.csproj">
@@ -63,12 +63,59 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="Converters\XmlNodeConverterTest.cs" />
<Compile Include="DateTimeTestClass.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
<Compile Include="TestObjects\CircularReferenceClass.cs" />
<Compile Include="TestObjects\ClassAndMemberConverterClass.cs" />
<Compile Include="TestObjects\ClassConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\ConstructorCaseSensitivityClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
<Compile Include="TestObjects\Invoice.cs" />
<Compile Include="TestObjects\JsonIgnoreAttributeTestClass.cs" />
<Compile Include="TestObjects\MemberConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\MethodExecutorObject.cs" />
<Compile Include="TestObjects\MyClass.cs" />
<Compile Include="TestObjects\Name.cs" />
<Compile Include="TestObjects\PersonRaw.cs" />
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
<Compile Include="TestObjects\ArticleCollection.cs" />
<Compile Include="TestObjects\ClassWithArray.cs" />
<Compile Include="TestObjects\ClassWithGuid.cs" />
<Compile Include="TestObjects\ConverableMembers.cs" />
<Compile Include="TestObjects\JsonIgnoreAttributeOnClassTestClass.cs" />
<Compile Include="Linq\JConstructorTests.cs" />
<Compile Include="Linq\JPropertyTests.cs" />
<Compile Include="TestObjects\MemberConverterClass.cs" />
<Compile Include="TestObjects\Product.cs" />
<Compile Include="TestObjects\ProductCollection.cs" />
<Compile Include="TestObjects\ProductShort.cs" />
<Compile Include="TestObjects\Store.cs" />
<Compile Include="TestObjects\StoreColor.cs" />
<Compile Include="TestObjects\Person.cs" />
<Compile Include="Schema\JsonSchemaBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaGeneratorTests.cs" />
<Compile Include="Schema\JsonSchemaTests.cs" />
<Compile Include="JsonRawTests.cs" />
<Compile Include="NullableDateTimeTestClass.cs" />
<Compile Include="TestObjects\DateTimeTestClass.cs" />
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="JsonTextReaderTest.cs" />
<Compile Include="JsonTextWriterTest.cs" />
@@ -80,11 +127,14 @@
<Compile Include="Linq\JTokenTests.cs" />
<Compile Include="Linq\JValueTests.cs" />
<Compile Include="Linq\LinqToJsonTest.cs" />
<Compile Include="NullableDateTimeTestClass.cs" />
<Compile Include="PerformanceTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SilverlightTests.cs" />
<Compile Include="TestFixtureBase.cs" />
<Compile Include="Converters\XmlNodeConverterTest.cs" />
<Compile Include="TestObjects\TypeClass.cs" />
<Compile Include="TestObjects\TypedSubHashtable.cs" />
<Compile Include="TestObjects\UserNullable.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.Silverlight.csproj">
@@ -76,9 +76,56 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
<Compile Include="TestObjects\CircularReferenceClass.cs" />
<Compile Include="TestObjects\ClassAndMemberConverterClass.cs" />
<Compile Include="TestObjects\ClassConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\ConstructorCaseSensitivityClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\IncompatibleJsonAttributeClass.cs" />
<Compile Include="TestObjects\Invoice.cs" />
<Compile Include="TestObjects\JsonIgnoreAttributeTestClass.cs" />
<Compile Include="TestObjects\MemberConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\MethodExecutorObject.cs" />
<Compile Include="TestObjects\MyClass.cs" />
<Compile Include="TestObjects\Name.cs" />
<Compile Include="TestObjects\PersonRaw.cs" />
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
<Compile Include="TestObjects\ArticleCollection.cs" />
<Compile Include="TestObjects\ClassWithArray.cs" />
<Compile Include="TestObjects\ClassWithGuid.cs" />
<Compile Include="TestObjects\ConverableMembers.cs" />
<Compile Include="TestObjects\JsonIgnoreAttributeOnClassTestClass.cs" />
<Compile Include="Linq\JConstructorTests.cs" />
<Compile Include="Linq\JPropertyTests.cs" />
<Compile Include="TestObjects\MemberConverterClass.cs" />
<Compile Include="TestObjects\Product.cs" />
<Compile Include="TestObjects\ProductCollection.cs" />
<Compile Include="TestObjects\ProductShort.cs" />
<Compile Include="TestObjects\Store.cs" />
<Compile Include="TestObjects\StoreColor.cs" />
<Compile Include="TestObjects\Person.cs" />
<Compile Include="Schema\JsonSchemaBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaGeneratorTests.cs" />
<Compile Include="Schema\JsonSchemaTests.cs" />
<Compile Include="JsonRawTests.cs" />
<Compile Include="NullableDateTimeTestClass.cs" />
<Compile Include="DateTimeTestClass.cs" />
<Compile Include="TestObjects\DateTimeTestClass.cs" />
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="JsonConvertTest.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
@@ -98,6 +145,9 @@
<Compile Include="SilverlightTests.cs" />
<Compile Include="TestFixtureBase.cs" />
<Compile Include="Converters\XmlNodeConverterTest.cs" />
<Compile Include="TestObjects\TypeClass.cs" />
<Compile Include="TestObjects\TypedSubHashtable.cs" />
<Compile Include="TestObjects\UserNullable.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.csproj">
@@ -20,7 +20,7 @@ namespace Newtonsoft.Json.Tests
/// </summary>
public class PerformanceTests : TestFixtureBase
{
private int Iterations = 5000;
private int Iterations = 100;
public enum SerializeMethod
{
@@ -0,0 +1,84 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Schema
{
public class ExtensionsTests : TestFixtureBase
{
[Test]
public void IsValid()
{
JsonSchema schema = JsonSchema.Parse("{'type':'integer'}");
JToken stringToken = JToken.FromObject("pie");
JToken integerToken = JToken.FromObject(1);
Assert.AreEqual(false, stringToken.IsValid(schema));
Assert.AreEqual(true, integerToken.IsValid(schema));
}
[Test]
public void ValidateWithEventHandler()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie lol");
List<string> errors = new List<string>();
stringToken.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
stringToken = JToken.FromObject("pie");
stringToken.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("String 'pie' does not match regex pattern 'lol'.", errors[0]);
}
[Test]
[ExpectedException(typeof(JsonSchemaException), ExpectedMessage = @"String 'pie' does not match regex pattern 'lol'.")]
public void ValidateWithOutEventHandlerFailure()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie");
stringToken.Validate(schema);
}
[Test]
public void ValidateWithOutEventHandlerSuccess()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie lol");
stringToken.Validate(schema);
}
}
}
@@ -0,0 +1,436 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaBuilderTests : TestFixtureBase
{
[Test]
public void Simple()
{
string json = @"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":
{
""type"":""array"",
""items"": {""type"":""string""}
}
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("A person", schema.Description);
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(2, schema.Properties.Count);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["name"].Type);
Assert.AreEqual(JsonSchemaType.Array, schema.Properties["hobbies"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["hobbies"].Items[0].Type);
}
[Test]
public void MultipleTypes()
{
string json = @"{
""description"":""Age"",
""type"":[""string"", ""integer""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Age", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Integer, schema.Type);
}
[Test]
public void MultipleItems()
{
string json = @"{
""description"":""MultipleItems"",
""type"":""array"",
""items"": [{""type"":""string""},{""type"":""array""}]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("MultipleItems", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Items[0].Type);
Assert.AreEqual(JsonSchemaType.Array, schema.Items[1].Type);
}
[Test]
public void AdditionalProperties()
{
string json = @"{
""description"":""AdditionalProperties"",
""type"":[""string"", ""integer""],
""additionalProperties"":{""type"":[""object"", ""boolean""]}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("AdditionalProperties", schema.Description);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Boolean, schema.AdditionalProperties.Type);
}
[Test]
public void Optional()
{
string json = @"{
""description"":""Optional"",
""optional"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Optional", schema.Description);
Assert.AreEqual(true, schema.Optional);
}
[Test]
public void ReadOnly()
{
string json = @"{
""description"":""ReadOnly"",
""readonly"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("ReadOnly", schema.Description);
Assert.AreEqual(true, schema.ReadOnly);
}
[Test]
public void Hidden()
{
string json = @"{
""description"":""Hidden"",
""hidden"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Hidden", schema.Description);
Assert.AreEqual(true, schema.Hidden);
}
[Test]
public void Id()
{
string json = @"{
""description"":""Id"",
""id"":""testid""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Id", schema.Description);
Assert.AreEqual("testid", schema.Id);
}
[Test]
public void Title()
{
string json = @"{
""description"":""Title"",
""title"":""testtitle""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Title", schema.Description);
Assert.AreEqual("testtitle", schema.Title);
}
[Test]
public void Pattern()
{
string json = @"{
""description"":""Pattern"",
""pattern"":""testpattern""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Pattern", schema.Description);
Assert.AreEqual("testpattern", schema.Pattern);
}
[Test]
public void Format()
{
string json = @"{
""description"":""Format"",
""format"":""testformat""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Format", schema.Description);
Assert.AreEqual("testformat", schema.Format);
}
[Test]
public void Requires()
{
string json = @"{
""description"":""Requires"",
""requires"":""PurpleMonkeyDishwasher""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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()
{
string json = @"{
""description"":""MinimumMaximum"",
""minimum"":1.1,
""maximum"":1.2,
""minItems"":1,
""maxItems"":2,
""minLength"":5,
""maxLength"":50,
""maxDecimal"":3,
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("MinimumMaximum", schema.Description);
Assert.AreEqual(1.1, schema.Minimum);
Assert.AreEqual(1.2, schema.Maximum);
Assert.AreEqual(1, schema.MinimumItems);
Assert.AreEqual(2, schema.MaximumItems);
Assert.AreEqual(5, schema.MinimumLength);
Assert.AreEqual(50, schema.MaximumLength);
Assert.AreEqual(3, schema.MaximumDecimals);
}
[Test]
public void DisallowSingleType()
{
string json = @"{
""description"":""DisallowSingleType"",
""disallow"":""string""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowSingleType", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Disallow);
}
[Test]
public void DisallowMultipleTypes()
{
string json = @"{
""description"":""DisallowMultipleTypes"",
""disallow"":[""string"",""number""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowMultipleTypes", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Float, schema.Disallow);
}
[Test]
public void DefaultPrimitiveType()
{
string json = @"{
""description"":""DefaultPrimitiveType"",
""default"":1.1
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultPrimitiveType", schema.Description);
Assert.AreEqual(1.1, (double)schema.Default);
}
[Test]
public void DefaultComplexType()
{
string json = @"{
""description"":""DefaultComplexType"",
""default"":{""pie"":true}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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()
{
string json = @"{
""description"":""Type"",
""type"":[""string"",""array""],
""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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]);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("CircularReference", schema.Description);
Assert.AreEqual("CircularReferenceArray", schema.Id);
Assert.AreEqual(JsonSchemaType.Array, schema.Type);
Assert.AreEqual(schema, schema.Items[0]);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Could not resolve schema reference for Id 'MyUnresolvedReference'.")]
public void UnresolvedReference()
{
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)));
}
}
}
@@ -0,0 +1,265 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Schema;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof (Dictionary<string, List<string>>));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": ""array"",
""items"": {
""type"": ""string""
}
}
}", json);
}
#if !PocketPC
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
Assert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""properties"": {
""TestField1"": {
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""type"": ""string""
},
""LastModified"": {
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""type"": ""string""
},
""FName"": {
""type"": [
""string"",
""null""
]
},
""LName"": {
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""type"": ""integer""
},
""NullableRoleId"": {
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""type"": [
""integer"",
""null""
]
},
""Active"": {
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof (Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void Generate_NumberFormatInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(NumberFormatInfo));
string json = schema.ToString();
Console.WriteLine(json);
// Assert.AreEqual(@"{
// ""type"": ""object"",
// ""additionalProperties"": {
// ""type"": ""array"",
// ""items"": {
// ""type"": ""string""
// }
// }
//}", json);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.")]
public void CircularReferenceError()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
}
}
@@ -0,0 +1,166 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Schema;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaModelBuilderTests : TestFixtureBase
{
[Test]
public void ExtendedComplex()
{
string first = @"{
""id"":""first"",
""type"":""object"",
""properties"":
{
""firstproperty"":{""type"":""string""},
""secondproperty"":{""type"":""string"",""maxLength"":10},
""thirdproperty"":{
""type"":""object"",
""properties"":
{
""thirdproperty_firstproperty"":{""type"":""string"",""maxLength"":10,""minLength"":7}
}
}
},
""additionalProperties"":{}
}";
string second = @"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""properties"":
{
""secondproperty"":{""type"":""any""},
""thirdproperty"":{
""extends"":{
""properties"":
{
""thirdproperty_firstproperty"":{""maxLength"":9,""minLength"":6,""pattern"":""hi2u""}
},
""additionalProperties"":{""maxLength"":9,""minLength"":6,""enum"":[""one"",""two""]}
},
""type"":""object"",
""properties"":
{
""thirdproperty_firstproperty"":{""pattern"":""hi""}
},
""additionalProperties"":{""type"":""string"",""enum"":[""two"",""three""]}
},
""fourthproperty"":{""type"":""string""}
},
""additionalProperties"":false
}";
JsonSchemaResolver resolver = new JsonSchemaResolver();
JsonSchema firstSchema = JsonSchema.Parse(first, resolver);
JsonSchema secondSchema = JsonSchema.Parse(second, resolver);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(secondSchema);
Assert.AreEqual(4, model.Properties.Count);
Assert.AreEqual(JsonSchemaType.String, model.Properties["firstproperty"].Type);
Assert.AreEqual(JsonSchemaType.String, model.Properties["secondproperty"].Type);
Assert.AreEqual(10, model.Properties["secondproperty"].MaximumLength);
Assert.AreEqual(null, model.Properties["secondproperty"].Enum);
Assert.AreEqual(null, model.Properties["secondproperty"].Patterns);
Assert.AreEqual(JsonSchemaType.Object, model.Properties["thirdproperty"].Type);
Assert.AreEqual(3, model.Properties["thirdproperty"].AdditionalProperties.Enum.Count);
Assert.AreEqual("two", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[0]);
Assert.AreEqual("three", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[1]);
Assert.AreEqual("one", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[2]);
Assert.AreEqual(JsonSchemaType.String, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Type);
Assert.AreEqual(9, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].MaximumLength);
Assert.AreEqual(7, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].MinimumLength);
Assert.AreEqual(2, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns.Count);
Assert.AreEqual("hi", model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns[0]);
Assert.AreEqual("hi2u", model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns[1]);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Properties);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Items);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].AdditionalProperties);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(schema);
Assert.AreEqual(JsonSchemaType.Array, model.Type);
Assert.AreEqual(model, model.Items[0]);
}
[Test]
public void Optional()
{
string schemaJson = @"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":{""type"":""string"",optional:true},
""age"":{""type"":""integer"",optional:true}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(schema);
Assert.AreEqual(JsonSchemaType.Object, model.Type);
Assert.AreEqual(3, model.Properties.Count);
Assert.AreEqual(false, model.Properties["name"].Optional);
Assert.AreEqual(true, model.Properties["hobbies"].Optional);
Assert.AreEqual(true, model.Properties["age"].Optional);
}
}
}
@@ -0,0 +1,118 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Schema;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaNodeTests : TestFixtureBase
{
[Test]
public void AddSchema()
{
string first = @"{
""id"":""first"",
""type"":""object"",
""properties"":
{
""firstproperty"":{""type"":""string"",""maxLength"":10},
""secondproperty"":{
""type"":""object"",
""properties"":
{
""secondproperty_firstproperty"":{""type"":""string"",""maxLength"":10,""minLength"":7}
}
}
},
""additionalProperties"":{}
}";
string second = @"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""properties"":
{
""firstproperty"":{""type"":""string""},
""secondproperty"":{
""extends"":{
""properties"":
{
""secondproperty_firstproperty"":{""maxLength"":9,""minLength"":6}
}
},
""type"":""object"",
""properties"":
{
""secondproperty_firstproperty"":{}
}
},
""thirdproperty"":{""type"":""string""}
},
""additionalProperties"":false
}";
JsonSchemaResolver resolver = new JsonSchemaResolver();
JsonSchema firstSchema = JsonSchema.Parse(first, resolver);
JsonSchema secondSchema = JsonSchema.Parse(second, resolver);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaNode node = modelBuilder.AddSchema(null, secondSchema);
Assert.AreEqual(2, node.Schemas.Count);
Assert.AreEqual(2, node.Properties["firstproperty"].Schemas.Count);
Assert.AreEqual(3, node.Properties["secondproperty"].Schemas.Count);
Assert.AreEqual(3, node.Properties["secondproperty"].Properties["secondproperty_firstproperty"].Schemas.Count);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaNode node = modelBuilder.AddSchema(null, schema);
Assert.AreEqual(1, node.Schemas.Count);
Assert.AreEqual(node, node.Items[0]);
}
}
}
@@ -0,0 +1,344 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Schema;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaTests : TestFixtureBase
{
[Test]
public void Extends()
{
string json;
JsonSchemaResolver resolver = new JsonSchemaResolver();
json = @"{
""id"":""first"",
""type"":""object"",
""additionalProperties"":{}
}";
JsonSchema first = JsonSchema.Parse(json, resolver);
json =
@"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""additionalProperties"":{""type"":""string""}
}";
JsonSchema second = JsonSchema.Parse(json, resolver);
Assert.AreEqual(first, second.Extends);
json =
@"{
""id"":""third"",
""type"":""object"",
""extends"":{""$ref"":""second""},
""additionalProperties"":false
}";
JsonSchema third = JsonSchema.Parse(json, resolver);
Assert.AreEqual(second, third.Extends);
Assert.AreEqual(first, third.Extends.Extends);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
third.WriteTo(jsonWriter, resolver);
string writtenJson = writer.ToString();
Assert.AreEqual(@"{
""id"": ""third"",
""type"": ""object"",
""additionalProperties"": false,
""extends"": {
""$ref"": ""second""
}
}", writtenJson);
StringWriter writer1 = new StringWriter();
JsonTextWriter jsonWriter1 = new JsonTextWriter(writer1);
jsonWriter1.Formatting = Formatting.Indented;
third.WriteTo(jsonWriter1);
writtenJson = writer1.ToString();
Assert.AreEqual(@"{
""id"": ""third"",
""type"": ""object"",
""additionalProperties"": false,
""extends"": {
""id"": ""second"",
""type"": ""object"",
""additionalProperties"": {
""type"": ""string""
},
""extends"": {
""id"": ""first"",
""type"": ""object"",
""additionalProperties"": {}
}
}
}", writtenJson);
}
[Test]
public void WriteTo_AdditionalProperties()
{
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""AdditionalProperties"",
""type"":[""string"", ""integer""],
""additionalProperties"":{""type"":[""object"", ""boolean""]}
}");
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""AdditionalProperties"",
""type"": [
""string"",
""integer""
],
""additionalProperties"": {
""type"": [
""boolean"",
""object""
]
}
}", json);
}
[Test]
public void WriteTo_Properties()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":
{
""type"":""array"",
""items"": {""type"":""string""}
}
}
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""A person"",
""type"": ""object"",
""properties"": {
""name"": {
""type"": ""string""
},
""hobbies"": {
""type"": ""array"",
""items"": {
""type"": ""string""
}
}
}
}", json);
}
[Test]
public void WriteTo_Enum()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""enum"": [
""string"",
""object"",
""array"",
""boolean"",
""number"",
""integer"",
""null"",
""any""
]
}", json);
}
[Test]
public void WriteTo_CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string writtenJson = writer.ToString();
Assert.AreEqual(@"{
""id"": ""CircularReferenceArray"",
""description"": ""CircularReference"",
""type"": ""array"",
""items"": {
""$ref"": ""CircularReferenceArray""
}
}", writtenJson);
}
[Test]
public void WriteTo_DisallowMultiple()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""disallow"":[""string"",""object"",""array""]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""disallow"": [
""string"",
""object"",
""array""
]
}", json);
}
[Test]
public void WriteTo_DisallowSingle()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""disallow"":""any""
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""disallow"": ""any""
}", json);
}
[Test]
public void WriteTo_MultipleItems()
{
JsonSchema schema = JsonSchema.Parse(@"{
""items"":[{},{}]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""items"": [
{},
{}
]
}", json);
}
}
}
@@ -0,0 +1,32 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public abstract class AbstractGenericBase<TKey>
{
public abstract TKey Id { get; set; }
}
}
@@ -0,0 +1,35 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ArgumentConverterPrecedenceClassConverter : ConverterPrecedenceClassConverter
{
public override string ConverterType
{
get { return "Argument"; }
}
}
}
@@ -0,0 +1,41 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Article
{
public string Name;
public Article()
{
}
public Article(string name)
{
Name = name;
}
}
}
@@ -0,0 +1,33 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ArticleCollection : List<Article>
{
}
}
@@ -0,0 +1,35 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class BadJsonPropertyClass
{
[JsonProperty("pie")]
public string Pie = "Yum";
public string pie = "PieChart!";
}
}
@@ -0,0 +1,39 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class CircularReferenceClass
{
[JsonProperty(IsRequired = true)]
public string Name { get; set; }
public CircularReferenceClass Child { get; set; }
}
}
@@ -0,0 +1,40 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonObject(Id = "MyExplicitId")]
public class CircularReferenceWithIdClass
{
[JsonProperty(IsRequired = true)]
public string Name { get; set; }
public CircularReferenceWithIdClass Child { get; set; }
}
}
@@ -0,0 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ClassAndMemberConverterClass
{
public ConverterPrecedenceClass DefaultConverter { get; set; }
[JsonConverter(typeof(MemberConverterPrecedenceClassConverter))]
public ConverterPrecedenceClass MemberConverter { get; set; }
}
}
@@ -0,0 +1,35 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ClassConverterPrecedenceClassConverter : ConverterPrecedenceClassConverter
{
public override string ConverterType
{
get { return "Class"; }
}
}
}
@@ -0,0 +1,54 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ClassWithArray
{
private readonly IList<long> bar;
private string foo;
public ClassWithArray()
{
bar = new List<Int64>() { int.MaxValue };
}
[JsonProperty("foo")]
public string Foo
{
get { return foo; }
set { foo = value; }
}
[JsonProperty(PropertyName = "bar")]
public IList<long> Bar
{
get { return bar; }
}
}
}
@@ -0,0 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ClassWithGuid
{
public Guid GuidField;
}
}
@@ -0,0 +1,41 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ConstructorCaseSensitivityClass
{
public string param1 { get; set; }
public string Param1 { get; set; }
public string Param2 { get; set; }
public ConstructorCaseSensitivityClass(string param1, string Param1, string param2)
{
this.param1 = param1;
this.Param1 = Param1;
this.Param2 = param2;
}
}
}
@@ -0,0 +1,48 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonObject]
public class ConverableMembers
{
public string String = "string";
public int Int32 = int.MaxValue;
public uint UInt32 = uint.MaxValue;
public byte Byte = byte.MaxValue;
public sbyte SByte = sbyte.MaxValue;
public short Short = short.MaxValue;
public ushort UShort = ushort.MaxValue;
public long Long = long.MaxValue;
public ulong ULong = long.MaxValue;
public double Double = double.MaxValue;
public float Float = float.MaxValue;
public DBNull DBNull = DBNull.Value;
public bool Bool = true;
public char Char = '\0';
}
}
@@ -0,0 +1,38 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonConverter(typeof(ClassConverterPrecedenceClassConverter))]
public class ConverterPrecedenceClass
{
public string TestValue { get; set; }
public ConverterPrecedenceClass(string testValue)
{
TestValue = testValue;
}
}
}
@@ -0,0 +1,63 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.TestObjects
{
public abstract class ConverterPrecedenceClassConverter : JsonConverter
{
public abstract string ConverterType { get; }
public override void WriteJson(JsonWriter writer, object value)
{
ConverterPrecedenceClass c = (ConverterPrecedenceClass)value;
JToken j = new JArray(ConverterType, c.TestValue);
j.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType)
{
JToken j = JArray.Load(reader);
string converter = (string)j[0];
if (converter != ConverterType)
throw new Exception(StringUtils.FormatWith("Serialize converter {0} and deserialize converter {1} do not match.", CultureInfo.InvariantCulture, converter, ConverterType));
string testValue = (string)j[1];
return new ConverterPrecedenceClass(testValue);
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ConverterPrecedenceClass));
}
}
}
@@ -28,7 +28,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests
namespace Newtonsoft.Json.Tests.TestObjects
{
public class DateTimeTestClass
{
@@ -0,0 +1,41 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.ComponentModel;
namespace Newtonsoft.Json.Tests.TestObjects
{
#if !PocketPC
[Description("DefaultValueAttributeTestClass description!")]
#endif
public class DefaultValueAttributeTestClass
{
[DefaultValue("TestProperty1Value")]
public string TestProperty1 { get; set; }
[DefaultValue(21)]
public int TestField1;
}
}
@@ -0,0 +1,32 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class DoubleClass
{
public double? Height { get; set; }
}
}
@@ -0,0 +1,32 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class GenericImpl : AbstractGenericBase<int>
{
public override int Id { get; set; }
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class GetOnlyPropertyClass
{
public string Field = "Field";
public string GetOnlyProperty
{
get { return "GetOnlyProperty"; }
}
}
}
@@ -0,0 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonConverter(typeof(IsoDateTimeConverter))]
public class IncompatibleJsonAttributeClass
{
}
}
@@ -0,0 +1,40 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.ComponentModel;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Invoice
{
public string Company { get; set; }
public decimal Amount { get; set; }
[DefaultValue(false)]
public bool Paid { get; set; }
[DefaultValue(null)]
public DateTime? PaidDate { get; set; }
}
}
@@ -0,0 +1,52 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonObject(MemberSerialization.OptIn)]
public class JsonIgnoreAttributeOnClassTestClass
{
private int _property = 21;
private int _ignoredProperty = 12;
[JsonProperty("TheField")]
public int Field;
[JsonProperty]
public int Property
{
get { return _property; }
}
public int IgnoredField;
[JsonProperty]
[JsonIgnore] // JsonIgnore should take priority
public int IgnoredProperty
{
get { return _ignoredProperty; }
}
}
}
@@ -0,0 +1,51 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class JsonIgnoreAttributeTestClass
{
private int _property = 21;
private int _ignoredProperty = 12;
public int Field;
public int Property
{
get { return _property; }
}
[JsonIgnore]
public int IgnoredField;
[JsonIgnore]
public int IgnoredProperty
{
get { return _ignoredProperty; }
}
[JsonIgnore]
public Product IgnoredObject = new Product();
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class MemberConverterClass
{
public DateTime DefaultConverter { get; set; }
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime MemberConverter { get; set; }
}
}
@@ -0,0 +1,35 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class MemberConverterPrecedenceClassConverter : ConverterPrecedenceClassConverter
{
public override string ConverterType
{
get { return "Member"; }
}
}
}
@@ -0,0 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class MethodExecutorObject
{
public string serverClassName;
public object[] serverMethodParams;
public string clientGetResultFunction;
}
}
@@ -0,0 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class MyClass
{
public int PreProperty { get; set; }
//public DateTime DateProperty { get; set; }
public int PostProperty { get; set; }
}
}
@@ -0,0 +1,41 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Name
{
public string personsName;
public List<PhoneNumber> pNumbers = new List<PhoneNumber>();
public Name(string personsName)
{
this.personsName = personsName;
}
}
}
@@ -0,0 +1,54 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.ComponentModel;
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonObject(Id = "Person", Title = "Title!", Description = "JsonObjectAttribute description!", MemberSerialization = MemberSerialization.OptIn)]
#if !PocketPC
[Description("DescriptionAttribute description!")]
#endif
public class Person
{
// "John Smith"
[JsonProperty]
public string Name { get; set; }
// "2000-12-15T22:11:03"
[JsonProperty]
//[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime BirthDate { get; set; }
// new Date(976918263055)
[JsonProperty]
//[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime LastModified { get; set; }
// not serialized
public string Department { get; set; }
}
}
@@ -0,0 +1,64 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class PersonRaw
{
private Guid _internalId;
private string _firstName;
private string _lastName;
private JsonRaw _rawContent;
[JsonIgnore]
public Guid InternalId
{
get { return _internalId; }
set { _internalId = value; }
}
[JsonProperty("first_name")]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public JsonRaw RawContent
{
get { return _rawContent; }
set { _rawContent = value; }
}
[JsonProperty("last_name")]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class PhoneNumber
{
public string phoneNumber;
public PhoneNumber(string phoneNumber)
{
this.phoneNumber = phoneNumber;
}
}
}
@@ -0,0 +1,54 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Product
{
public string Name;
public DateTime Expiry = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public decimal Price;
public string[] Sizes;
public override bool Equals(object obj)
{
if (obj is Product)
{
Product p = (Product)obj;
return (p.Name == Name && p.Expiry == Expiry && p.Price == Price);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return (Name ?? string.Empty).GetHashCode();
}
}
}
@@ -0,0 +1,33 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ProductCollection : List<Product>
{
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class ProductShort
{
public string Name;
public DateTime Expiry;
//public decimal Price;
public string[] Sizes;
}
}
@@ -0,0 +1,47 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class RequiredMembersClass
{
[JsonProperty(IsRequired = true)]
public string FirstName { get; set; }
[JsonProperty]
public string MiddleName { get; set; }
[JsonProperty(IsRequired = true)]
public string LastName { get; set; }
[JsonProperty(IsRequired = true)]
public DateTime BirthDate { get; set; }
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class SetOnlyPropertyClass
{
public string Field = "Field";
public string SetOnlyProperty
{
set { }
}
}
}
@@ -0,0 +1,62 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Store
{
public StoreColor Color = StoreColor.Yellow;
public DateTimeOffset Establised = new DateTimeOffset(2010, 1, 22, 1, 1, 1, TimeSpan.Zero);
public double Width = 1.1;
public int Employees = 999;
public int[] RoomsPerFloor = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public bool Open = false;
public char Symbol = '@';
public List<string> Mottos = new List<string>();
public decimal Cost = 100980.1M;
public string Escape = "\r\n\t\f\b?{\\r\\n\"\'";
public List<Product> product = new List<Product>();
public Store()
{
Mottos.Add("Hello World");
Mottos.Add("öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~");
Mottos.Add(null);
Mottos.Add(" ");
Product rocket = new Product();
rocket.Name = "Rocket";
rocket.Expiry = new DateTime(2000, 2, 2, 23, 1, 30, DateTimeKind.Utc);
Product alien = new Product();
alien.Name = "Alien";
product.Add(rocket);
product.Add(alien);
}
}
}
@@ -0,0 +1,35 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public enum StoreColor
{
Black,
Red,
Yellow,
White
}
}
@@ -0,0 +1,34 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class TypeClass
{
public Type TypeProperty { get; set; }
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections;
namespace Newtonsoft.Json.Tests.TestObjects
{
#if !SILVERLIGHT
public class TypedSubHashtable
{
public string Name;
public Hashtable Hash;
}
#endif
}
@@ -0,0 +1,40 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class UserNullable
{
public Guid Id;
public string FName;
public string LName;
public int RoleId;
public int? NullableRoleId;
public int? NullRoleId;
public bool? Active;
}
}
+72
View File
@@ -0,0 +1,72 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> how to serialize the object.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public sealed class JsonArrayAttribute : JsonContainerAttribute
{
private bool _allowNullItems;
public bool AllowNullItems
{
get { return _allowNullItems; }
set { _allowNullItems = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayAttribute"/> class.
/// </summary>
public JsonArrayAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectAttribute"/> class with a flag indicating whether the array can contain null items
/// </summary>
/// <param name="allowNullItems">A flag indicating whether the array can contain null items.</param>
public JsonArrayAttribute(bool allowNullItems)
{
_allowNullItems = allowNullItems;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
public JsonArrayAttribute(string id)
: base(id)
{
}
}
}
@@ -0,0 +1,59 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> how to serialize the object.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public abstract class JsonContainerAttribute : Attribute
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonContainerAttribute"/> class.
/// </summary>
public JsonContainerAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonContainerAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
public JsonContainerAttribute(string id)
{
Id = id;
}
}
}
+11 -3
View File
@@ -38,7 +38,7 @@ using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JavaScript types.
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
public static class JsonConvert
{
@@ -255,7 +255,7 @@ namespace Newtonsoft.Json
/// <returns>A Json string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return value.ToString("R", CultureInfo.InvariantCulture);
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
@@ -265,7 +265,15 @@ namespace Newtonsoft.Json
/// <returns>A Json string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return value.ToString("R", CultureInfo.InvariantCulture);
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1)
return text;
return text + ".0";
}
/// <summary>
+10 -1
View File
@@ -34,7 +34,7 @@ namespace Newtonsoft.Json
/// Instructs the <see cref="JsonSerializer"/> how to serialize the object.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public sealed class JsonObjectAttribute : Attribute
public sealed class JsonObjectAttribute : JsonContainerAttribute
{
private MemberSerialization _memberSerialization = MemberSerialization.OptOut;
@@ -63,5 +63,14 @@ namespace Newtonsoft.Json
{
MemberSerialization = memberSerialization;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
public JsonObjectAttribute(string id)
: base(id)
{
}
}
}
@@ -9,6 +9,7 @@ namespace Newtonsoft.Json
public sealed class JsonPropertyAttribute : Attribute
{
private string _propertyName;
private bool _isRequired;
/// <summary>
/// Gets or sets the name of the property.
@@ -20,6 +21,12 @@ namespace Newtonsoft.Json
set { _propertyName = value; }
}
public bool IsRequired
{
get { return _isRequired; }
set { _isRequired = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class.
/// </summary>
+8 -10
View File
@@ -25,9 +25,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
@@ -117,21 +115,21 @@ namespace Newtonsoft.Json
private int _top;
private List<JsonTokenType> _stack;
private readonly List<JsonTokenType> _stack;
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public char QuoteChar
public virtual char QuoteChar
{
get { return _quoteChar; }
protected set { _quoteChar = value; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Gets the type of the current Json token.
/// </summary>
public JsonToken TokenType
public virtual JsonToken TokenType
{
get { return _token; }
}
@@ -139,7 +137,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets the text value of the current Json token.
/// </summary>
public object Value
public virtual object Value
{
get { return _value; }
}
@@ -147,7 +145,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current Json token.
/// </summary>
public Type ValueType
public virtual Type ValueType
{
get { return _valueType; }
}
@@ -156,7 +154,7 @@ namespace Newtonsoft.Json
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public int Depth
public virtual int Depth
{
get
{
@@ -331,7 +329,7 @@ namespace Newtonsoft.Json
}
}
private bool IsStartToken(JsonToken token)
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
+44 -113
View File
@@ -30,6 +30,7 @@ using System.IO;
using System.Collections;
using System.Reflection;
using System.ComponentModel;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Linq;
@@ -44,9 +45,7 @@ namespace Newtonsoft.Json
/// </summary>
public class JsonSerializer
{
private static readonly Dictionary<ICustomAttributeProvider, Type> ConverterTypeCache = new Dictionary<ICustomAttributeProvider, Type>();
private static readonly Dictionary<Type, MemberMappingCollection> TypeMemberMappingsCache = new Dictionary<Type,MemberMappingCollection>();
#region Properties
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private ObjectCreationHandling _objectCreationHandling;
@@ -145,6 +144,7 @@ namespace Newtonsoft.Json
return _converters;
}
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
@@ -244,7 +244,7 @@ namespace Newtonsoft.Json
if (objectType == null)
throw new ArgumentNullException("objectType");
converter = GetConverter(objectType, objectType);
converter = JsonTypeReflector.GetConverter(objectType, objectType);
return (converter != null);
}
@@ -282,7 +282,7 @@ namespace Newtonsoft.Json
{
value = CreateJToken(reader);
}
else if (typeof(IDictionary).IsAssignableFrom(objectType) || ReflectionUtils.ImplementsGenericDefinition(objectType, typeof(IDictionary<,>)))
else if (CollectionUtils.IsDictionaryType(objectType))
{
if (existingValue == null)
value = CreateAndPopulateDictionary(reader, objectType);
@@ -363,110 +363,16 @@ namespace Newtonsoft.Json
}
}
private MemberMappingCollection GetMemberMappings(Type objectType)
protected virtual JsonMemberMappingCollection GetMemberMappings(Type objectType)
{
MemberMappingCollection memberMappings;
ValidationUtils.ArgumentNotNull(objectType, "objectType");
if (TypeMemberMappingsCache.TryGetValue(objectType, out memberMappings))
return memberMappings;
memberMappings = CreateMemberMappings(objectType);
TypeMemberMappingsCache[objectType] = memberMappings;
return memberMappings;
}
private MemberMappingCollection CreateMemberMappings(Type objectType)
{
MemberSerialization memberSerialization = GetObjectMemberSerialization(objectType);
List<MemberInfo> members = GetSerializableMembers(objectType);
if (members == null)
throw new JsonSerializationException("Null collection of seralizable members returned.");
MemberMappingCollection memberMappings = new MemberMappingCollection();
foreach (MemberInfo member in members)
{
JsonPropertyAttribute propertyAttribute = ReflectionUtils.GetAttribute<JsonPropertyAttribute>(member, true);
bool hasIgnoreAttribute = member.IsDefined(typeof(JsonIgnoreAttribute), true);
string mappedName = (propertyAttribute != null && propertyAttribute.PropertyName != null)
? propertyAttribute.PropertyName
: member.Name;
bool ignored = (hasIgnoreAttribute
|| (memberSerialization == MemberSerialization.OptIn && propertyAttribute == null));
bool readable = ReflectionUtils.CanReadMemberValue(member);
bool writable = ReflectionUtils.CanSetMemberValue(member);
JsonConverter memberConverter = GetConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));
DefaultValueAttribute defaultValueAttribute = ReflectionUtils.GetAttribute<DefaultValueAttribute>(member, true);
object defaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;
MemberMapping memberMapping = new MemberMapping(mappedName, member, ignored, readable, writable, memberConverter, defaultValue);
memberMappings.AddMapping(memberMapping);
}
return memberMappings;
}
/// <summary>
/// Gets the serializable members for the given <see cref="Type"/>.
/// </summary>
/// <param name="objectType">The object <see cref="Type"/> to get seralizable members for.</param>
/// <returns>Seralizable members for the given type.</returns>
protected virtual List<MemberInfo> GetSerializableMembers(Type objectType)
{
return ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.Instance);
}
private static MemberSerialization GetObjectMemberSerialization(Type objectType)
{
JsonObjectAttribute objectAttribute = ReflectionUtils.GetAttribute<JsonObjectAttribute>(objectType, true);
if (objectAttribute == null)
return MemberSerialization.OptOut;
else
return objectAttribute.MemberSerialization;
}
private JsonConverter GetConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
{
Type converterType;
if (!ConverterTypeCache.TryGetValue(attributeProvider, out converterType))
{
JsonConverterAttribute converterAttribute = ReflectionUtils.GetAttribute<JsonConverterAttribute>(attributeProvider, true);
converterType = (converterAttribute != null)
? converterAttribute.ConverterType
: null;
ConverterTypeCache[attributeProvider] = converterType;
}
if (converterType != null)
{
JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);
if (!memberConverter.CanConvert(targetConvertedType))
throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name));
return memberConverter;
}
return null;
return JsonTypeReflector.GetMemberMappings(objectType);
}
private void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName)
{
if (!reader.Read())
throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
MemberMappingCollection memberMappings = GetMemberMappings(targetType);
JsonMemberMappingCollection memberMappings = GetMemberMappings(targetType);
Type memberType;
object value;
@@ -474,7 +380,7 @@ namespace Newtonsoft.Json
// otherwise test if target is a dictionary and assign value with the key if it is
if (memberMappings.Contains(memberName))
{
MemberMapping memberMapping = memberMappings[memberName];
JsonMemberMapping memberMapping = memberMappings[memberName];
if (memberMapping.Ignored)
{
@@ -503,7 +409,7 @@ namespace Newtonsoft.Json
return;
}
value = CreateObject(reader, memberType, (useExistingValue) ? currentValue : null, GetConverter(memberMapping.Member, memberType));
value = CreateObject(reader, memberType, (useExistingValue) ? currentValue : null, JsonTypeReflector.GetConverter(memberMapping.Member, memberType));
if (_nullValueHandling == NullValueHandling.Ignore && value == null)
return;
@@ -603,7 +509,7 @@ namespace Newtonsoft.Json
// create a dictionary to put retrieved values into
IDictionary<ParameterInfo, object> constructorParameters = c.GetParameters().ToDictionary(p => p, p => (object)null);
MemberMappingCollection mappings = GetMemberMappings(objectType);
JsonMemberMappingCollection mappings = GetMemberMappings(objectType);
bool exit = false;
while (!exit && reader.Read())
@@ -616,7 +522,7 @@ namespace Newtonsoft.Json
throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, memberName).Key;
MemberMapping mapping;
JsonMemberMapping mapping;
if (matchingConstructorParameter != null && mappings.TryGetMapping(memberName, out mapping) && !mapping.Ignored)
{
@@ -644,6 +550,15 @@ namespace Newtonsoft.Json
private object PopulateObject(object newObject, JsonReader reader, Type objectType)
{
JsonMemberMappingCollection memberMappings = GetMemberMappings(objectType);
Dictionary<string, bool> requiredMappings =
memberMappings.Where(m => m.Required).ToDictionary(m => m.MappingName, m => false);
//List<RequiredMemberContext> requiredMappingContexts =
// memberMappings.Where(m => m.Required).Select(m => new RequiredMemberContext(m.MappingName, false)).ToList();
//ObjectContext context = new ObjectContext(newObject, requiredMappingContexts);
//DeserializeStack.Add(context);
while (reader.Read())
{
switch (reader.TokenType)
@@ -651,9 +566,25 @@ namespace Newtonsoft.Json
case JsonToken.PropertyName:
string memberName = reader.Value.ToString();
if (!reader.Read())
throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
if (reader.TokenType != JsonToken.Null)
{
if (requiredMappings.ContainsKey(memberName))
requiredMappings[memberName] = true;
}
SetObjectMember(reader, newObject, objectType, memberName);
break;
case JsonToken.EndObject:
foreach (KeyValuePair<string, bool> requiredMapping in requiredMappings)
{
if (!requiredMapping.Value)
throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, requiredMapping.Key));
}
// TODO: move below, change to RemoveAt
//DeserializeStack.Remove(context);
return newObject;
default:
throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
@@ -772,7 +703,7 @@ namespace Newtonsoft.Json
return false;
}
private void WriteMemberInfoProperty(JsonWriter writer, object value, MemberMapping memberMapping)
private void WriteMemberInfoProperty(JsonWriter writer, object value, JsonMemberMapping memberMapping)
{
MemberInfo member = memberMapping.Member;
string propertyName = memberMapping.MappingName;
@@ -819,7 +750,7 @@ namespace Newtonsoft.Json
TypeConverter converter = TypeDescriptor.GetConverter(objectType);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null && !(converter is ComponentConverter) && converter.GetType() != typeof(TypeConverter))
if (converter != null && !(converter is ComponentConverter) && (converter.GetType() != typeof(TypeConverter) || value is Type))
{
if (converter.CanConvertTo(typeof(string)))
{
@@ -828,7 +759,7 @@ namespace Newtonsoft.Json
}
}
#else
if (value is Guid)
if (value is Guid || value is Type)
{
writer.WriteValue(value.ToString());
return;
@@ -839,9 +770,9 @@ namespace Newtonsoft.Json
writer.WriteStartObject();
MemberMappingCollection memberMappings = GetMemberMappings(objectType);
JsonMemberMappingCollection memberMappings = GetMemberMappings(objectType);
foreach (MemberMapping memberMapping in memberMappings)
foreach (JsonMemberMapping memberMapping in memberMappings)
{
if (!memberMapping.Ignored && memberMapping.Readable)
WriteMemberInfoProperty(writer, value, memberMapping);
@@ -849,7 +780,7 @@ namespace Newtonsoft.Json
writer.WriteEndObject();
writer.SerializeStack.Remove(value);
writer.SerializeStack.RemoveAt(writer.SerializeStack.Count - 1);
}
private void SerializeEnumerable(JsonWriter writer, IEnumerable values)
+5
View File
@@ -381,12 +381,16 @@ namespace Newtonsoft.Json
private bool ParseProperty()
{
char quoteChar;
if (ValidIdentifierChar(_currentChar))
{
quoteChar = '\0';
ParseUnquotedProperty();
}
else if (_currentChar == '"' || _currentChar == '\'')
{
quoteChar = _currentChar;
ParseQuotedProperty(_currentChar);
}
else
@@ -401,6 +405,7 @@ namespace Newtonsoft.Json
}
SetToken(JsonToken.PropertyName, _buffer.ToString());
QuoteChar = quoteChar;
_buffer.Position = 0;
return true;
+535
View File
@@ -0,0 +1,535 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Newtonsoft.Json
{
public class JsonValidatingReader : JsonReader
{
private class SchemaScope
{
private readonly JsonTokenType _tokenType;
private readonly JsonSchemaModel _schema;
private readonly Dictionary<string, bool> _requiredProperties;
public string CurrentPropertyName { get; set; }
public int ArrayItemCount { get; set; }
public JsonSchemaModel Schema
{
get { return _schema; }
}
public Dictionary<string, bool> RequiredProperties
{
get { return _requiredProperties; }
}
public JsonTokenType TokenType
{
get { return _tokenType; }
}
public SchemaScope(JsonTokenType tokenType, JsonSchemaModel schema)
{
_tokenType = tokenType;
_schema = schema;
if (_schema != null && _schema.Properties != null)
{
_requiredProperties = GetRequiredProperties(_schema).Distinct().ToDictionary(p => p, p => false);
}
}
private IEnumerable<string> GetRequiredProperties(JsonSchemaModel schema)
{
return schema.Properties.Where(p => !p.Value.Optional).Select(p => p.Key);
//if (schema == null)
// return Enumerable.Empty<string>();
//IEnumerable<string> extendedRequiredProperties = GetRequiredProperties(schema.Extends);
//if (_schema.Properties == null)
// return extendedRequiredProperties;
//return extendedRequiredProperties.Union(schema.Properties.Where(p => !(p.Value.Optional ?? false)).Select(p => p.Key));
}
}
private readonly JsonReader _reader;
private readonly Stack<SchemaScope> _stack;
private JsonSchema _schema;
private JsonSchemaModel _model;
private SchemaScope _currentScope;
public event ValidationEventHandler ValidationEventHandler;
public override object Value
{
get { return _reader.Value; }
}
public override int Depth
{
get { return _reader.Depth; }
}
public override char QuoteChar
{
get { return _reader.QuoteChar; }
protected internal set { }
}
public override JsonToken TokenType
{
get { return _reader.TokenType; }
}
public override Type ValueType
{
get { return _reader.ValueType; }
}
private void Push(SchemaScope scope)
{
_stack.Push(scope);
_currentScope = scope;
}
private SchemaScope Pop()
{
SchemaScope poppedScope = _stack.Pop();
_currentScope = (_stack.Count != 0)
? _stack.Peek()
: null;
return poppedScope;
}
private JsonSchemaModel CurrentSchema
{
get { return _currentScope.Schema; }
}
private JsonSchemaModel CurrentMemberSchema
{
get
{
if (_currentScope == null)
return _model;
if (_currentScope.Schema == null)
return null;
switch (_currentScope.TokenType)
{
case JsonTokenType.None:
return _currentScope.Schema;
case JsonTokenType.Object:
if (_currentScope.CurrentPropertyName == null)
throw new Exception("CurrentPropertyName has not been set on scope.");
JsonSchemaModel propertySchema;
if (CurrentSchema.Properties.TryGetValue(_currentScope.CurrentPropertyName, out propertySchema))
return propertySchema;
return (CurrentSchema.AllowAdditionalProperties) ? CurrentSchema.AdditionalProperties : null;
case JsonTokenType.Array:
if (!CollectionUtils.IsNullOrEmpty(CurrentSchema.Items))
{
if (CurrentSchema.Items.Count == 1)
return CurrentSchema.Items[0];
if (CurrentSchema.Items.Count > (_currentScope.ArrayItemCount - 1))
return CurrentSchema.Items[_currentScope.ArrayItemCount - 1];
}
return (CurrentSchema.AllowAdditionalProperties) ? CurrentSchema.AdditionalProperties : null;
case JsonTokenType.Constructor:
return null;
default:
throw new ArgumentOutOfRangeException("TokenType", "Unexpected token type: {0}".FormatWith(CultureInfo.InvariantCulture, _currentScope.TokenType));
}
}
}
private void RaiseError(string message, JsonSchemaModel schema)
{
OnValidationEvent(new JsonSchemaException(message));
}
private void OnValidationEvent(JsonSchemaException exception)
{
ValidationEventHandler handler = ValidationEventHandler;
if (handler != null)
handler(this, new ValidationEventArgs(exception));
else
throw exception;
}
public JsonValidatingReader(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
_reader = reader;
_stack = new Stack<SchemaScope>();
}
public JsonSchema Schema
{
get { return _schema; }
set
{
if (TokenType != JsonToken.None)
throw new Exception("Cannot change schema while validating JSON.");
_schema = value;
_model = null;
}
}
public JsonReader Reader
{
get { return _reader; }
}
private void ValidateInEnumAndNotDisallowed(JsonSchemaModel schema)
{
if (schema == null)
return;
JToken value = new JValue(_reader.Value);
if (schema.Enum != null)
{
if (!schema.Enum.Contains(value, new JTokenEqualityComparer()))
RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, value),
schema);
}
JsonSchemaType? currentNodeType = GetCurrentNodeSchemaType();
if (currentNodeType != null)
{
if (JsonSchemaGenerator.HasFlag(schema.Disallow, currentNodeType.Value))
RaiseError("Type {0} is disallowed.".FormatWith(CultureInfo.InvariantCulture, currentNodeType), schema);
}
}
private JsonSchemaType? GetCurrentNodeSchemaType()
{
switch (_reader.TokenType)
{
case JsonToken.StartObject:
return JsonSchemaType.Object;
case JsonToken.StartArray:
return JsonSchemaType.Array;
case JsonToken.Integer:
return JsonSchemaType.Integer;
case JsonToken.Float:
return JsonSchemaType.Float;
case JsonToken.String:
return JsonSchemaType.String;
case JsonToken.Boolean:
return JsonSchemaType.Boolean;
case JsonToken.Null:
return JsonSchemaType.Null;
default:
return null;
}
}
public override bool Read()
{
if (!_reader.Read())
return false;
if (_reader.TokenType == JsonToken.Comment)
return true;
// first time Read has been called. build model
if (_model == null)
{
JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder();
_model = builder.Build(_schema);
}
switch (_reader.TokenType)
{
case JsonToken.StartObject:
ProcessValue();
JsonSchemaModel objectSchema = (ValidateObject(CurrentMemberSchema))
? CurrentMemberSchema
: null;
Push(new SchemaScope(JsonTokenType.Object, objectSchema));
break;
case JsonToken.StartArray:
ProcessValue();
JsonSchemaModel arraySchema = (ValidateArray(CurrentMemberSchema))
? CurrentMemberSchema
: null;
Push(new SchemaScope(JsonTokenType.Array, arraySchema));
break;
case JsonToken.StartConstructor:
Push(new SchemaScope(JsonTokenType.Constructor, null));
break;
case JsonToken.PropertyName:
ValidatePropertyName(CurrentSchema);
break;
case JsonToken.Raw:
break;
case JsonToken.Integer:
ProcessValue();
ValidateInteger(CurrentMemberSchema);
break;
case JsonToken.Float:
ProcessValue();
ValidateFloat(CurrentMemberSchema);
break;
case JsonToken.String:
ProcessValue();
ValidateString(CurrentMemberSchema);
break;
case JsonToken.Boolean:
ProcessValue();
ValidateBoolean(CurrentMemberSchema);
break;
case JsonToken.Null:
ProcessValue();
ValidateNull(CurrentMemberSchema);
break;
case JsonToken.Undefined:
break;
case JsonToken.EndObject:
ValidateEndObject(CurrentSchema);
Pop();
break;
case JsonToken.EndArray:
ValidateEndArray(CurrentSchema);
Pop();
break;
case JsonToken.EndConstructor:
Pop();
break;
case JsonToken.Date:
break;
default:
throw new ArgumentOutOfRangeException();
}
return true;
}
private void ValidateEndObject(JsonSchemaModel schema)
{
if (schema == null)
return;
Dictionary<string, bool> requiredProperties = _currentScope.RequiredProperties;
if (requiredProperties != null)
{
List<string> unmatchedRequiredProperties =
requiredProperties.Where(kv => !kv.Value).Select(kv => kv.Key).ToList();
if (unmatchedRequiredProperties.Count > 0)
RaiseError("Non-optional properties are missing from object: {0}".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", unmatchedRequiredProperties.ToArray())), schema);
}
}
private void ValidateEndArray(JsonSchemaModel schema)
{
if (schema == null)
return;
int arrayItemCount = _currentScope.ArrayItemCount;
if (schema.MaximumItems != null && arrayItemCount > schema.MaximumItems)
RaiseError("Array item count {0} exceeds maximum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MaximumItems), schema);
if (schema.MinimumItems != null && arrayItemCount < schema.MinimumItems)
RaiseError("Array item count {0} is less than minimum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MinimumItems), schema);
}
private void ValidateNull(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Null))
return;
ValidateInEnumAndNotDisallowed(schema);
}
private void ValidateBoolean(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Boolean))
return;
ValidateInEnumAndNotDisallowed(schema);
}
private void ValidateString(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.String))
return;
ValidateInEnumAndNotDisallowed(schema);
string value = _reader.Value.ToString();
if (schema.MaximumLength != null && value.Length > schema.MaximumLength)
RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), schema);
if (schema.MinimumLength != null && value.Length < schema.MinimumLength)
RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), schema);
if (schema.Patterns != null)
{
foreach (string pattern in schema.Patterns)
{
if (!Regex.IsMatch(value, pattern))
RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, pattern), schema);
}
}
}
private void ValidateInteger(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Integer))
return;
ValidateInEnumAndNotDisallowed(schema);
long value = Convert.ToInt64(_reader.Value, CultureInfo.InvariantCulture);
if (schema.Maximum != null && value > schema.Maximum)
RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema);
if (schema.Minimum != null && value < schema.Minimum)
RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema);
}
private void ProcessValue()
{
if (_currentScope != null && _currentScope.TokenType == JsonTokenType.Array)
{
_currentScope.ArrayItemCount++;
if (CurrentSchema != null && CurrentSchema.Items != null && CurrentSchema.Items.Count > 1 && _currentScope.ArrayItemCount >= CurrentSchema.Items.Count)
RaiseError("Index {0} has not been defined and schema does not allow additional items.".FormatWith(CultureInfo.InvariantCulture, _currentScope.ArrayItemCount), CurrentSchema);
}
}
private void ValidateFloat(JsonSchemaModel schema)
{
if (schema == null)
return;
if (!TestType(schema, JsonSchemaType.Float))
return;
ValidateInEnumAndNotDisallowed(schema);
double value = Convert.ToDouble(_reader.Value);
if (schema.Maximum != null && value > schema.Maximum)
RaiseError("Float {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema);
if (schema.Minimum != null && value < schema.Minimum)
RaiseError("Float {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema);
if (schema.MaximumDecimals != null && MathUtils.GetDecimalPlaces(value) > schema.MaximumDecimals)
RaiseError("Float {0} exceeds the maximum allowed number decimal places of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.MaximumDecimals), schema);
}
private void ValidatePropertyName(JsonSchemaModel schema)
{
if (schema == null)
return;
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
if (_currentScope.RequiredProperties.ContainsKey(propertyName))
_currentScope.RequiredProperties[propertyName] = true;
if (!schema.Properties.ContainsKey(propertyName))
{
IList<string> definedProperties = schema.Properties.Select(p => p.Key).ToList();
if (!schema.AllowAdditionalProperties && !definedProperties.Contains(propertyName))
{
RaiseError("Property '{0}' has not been defined and schema does not allow additional properties.".FormatWith(CultureInfo.InvariantCulture, propertyName), schema);
}
}
_currentScope.CurrentPropertyName = propertyName;
}
private bool ValidateArray(JsonSchemaModel schema)
{
if (schema == null)
return true;
return (TestType(schema, JsonSchemaType.Array));
}
private bool ValidateObject(JsonSchemaModel schema)
{
if (schema == null)
return true;
return (TestType(schema, JsonSchemaType.Object));
}
private bool TestType(JsonSchemaModel currentSchema, JsonSchemaType currentType)
{
if (!JsonSchemaGenerator.HasFlag(currentSchema.Type, currentType))
{
RaiseError("Invalid type. Expected {0} but got {1}.".FormatWith(CultureInfo.InvariantCulture, currentSchema.Type, currentType), currentSchema);
return false;
}
return true;
}
}
}
+5 -2
View File
@@ -122,9 +122,9 @@ namespace Newtonsoft.Json
private int _top;
private List<JsonTokenType> _stack;
private List<object> _serializeStack;
private State _currentState;
private Formatting _formatting;
private List<object> _serializeStack;
internal List<object> SerializeStack
{
@@ -192,7 +192,7 @@ namespace Newtonsoft.Json
/// </summary>
public JsonWriter()
{
_stack = new List<JsonTokenType>(1);
_stack = new List<JsonTokenType>(8);
_stack.Add(JsonTokenType.None);
_currentState = State.Start;
_formatting = Formatting.None;
@@ -529,6 +529,9 @@ namespace Newtonsoft.Json
case JsonTokenType.Array:
_currentState = State.Array;
break;
case JsonTokenType.Constructor:
_currentState = State.Array;
break;
case JsonTokenType.None:
_currentState = State.Start;
break;
+9 -10
View File
@@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Linq
/// Loads an <see cref="JArray"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JArray"/>.</param>
/// <returns>A <see cref="JArray"/> that contains the XML that was read from the specified <see cref="JsonReader"/>.</returns>
/// <returns>A <see cref="JArray"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static JArray Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
@@ -105,14 +105,13 @@ namespace Newtonsoft.Json.Linq
throw new Exception("Error reading JArray from JsonReader.");
}
if (reader.TokenType != JsonToken.StartArray)
{
throw new Exception("Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
else
{
if (!reader.Read())
throw new Exception("Error reading JArray from JsonReader.");
}
throw new Exception(
"Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
if (!reader.Read())
throw new Exception("Error reading JArray from JsonReader.");
JArray a = new JArray();
a.ReadContentFrom(reader);
@@ -145,7 +144,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JArray"/>.</param>
/// <returns>A <see cref="JArray"/> with the values of the specified object</returns>
public static JArray FromObject(object o)
public static new JArray FromObject(object o)
{
JToken token = FromObjectInternal(o);
+28
View File
@@ -160,5 +160,33 @@ namespace Newtonsoft.Json.Linq
{
return _name.GetHashCode() ^ ContentsHashCode();
}
/// <summary>
/// Loads an <see cref="JConstructor"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param>
/// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static JConstructor Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JConstructor from JsonReader.");
}
if (reader.TokenType != JsonToken.StartConstructor)
throw new Exception(
"Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
JConstructor c = new JConstructor((string)reader.Value);
if (!reader.Read())
throw new Exception("Error reading JConstructor from JsonReader.");
c.ReadContentFrom(reader);
return c;
}
}
}
+5 -20
View File
@@ -26,7 +26,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Diagnostics;
@@ -191,22 +190,6 @@ namespace Newtonsoft.Json.Linq
}
}
internal static JToken FromObjectInternal(object o)
{
ValidationUtils.ArgumentNotNull(o, "o");
JsonSerializer jsonSerializer = new JsonSerializer();
JToken token;
using (JsonTokenWriter jsonWriter = new JsonTokenWriter())
{
jsonSerializer.Serialize(jsonWriter, o);
token = jsonWriter.Token;
}
return token;
}
internal static JToken GetIndex(JContainer c, object o)
{
return c.Children().ElementAt((int)o);
@@ -387,10 +370,12 @@ namespace Newtonsoft.Json.Linq
do
{
if (parent is JProperty)
if (parent is JProperty && ((JProperty)parent).Value != null)
{
if (((JProperty)parent).Value != null)
parent = parent.Parent;
if (parent == this)
return;
parent = parent.Parent;
}
switch (r.TokenType)
+8 -10
View File
@@ -181,7 +181,7 @@ namespace Newtonsoft.Json.Linq
/// Loads an <see cref="JObject"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param>
/// <returns>A <see cref="JObject"/> that contains the XML that was read from the specified <see cref="JsonReader"/>.</returns>
/// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static JObject Load(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
@@ -192,14 +192,12 @@ namespace Newtonsoft.Json.Linq
throw new Exception("Error reading JObject from JsonReader.");
}
if (reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
else
{
if (!reader.Read())
throw new Exception("Error reading JObject from JsonReader.");
}
throw new Exception(
"Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
if (!reader.Read())
throw new Exception("Error reading JObject from JsonReader.");
JObject o = new JObject();
o.ReadContentFrom(reader);
@@ -224,7 +222,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JObject"/>.</param>
/// <returns>A <see cref="JObject"/> with the values of the specified object</returns>
public static JObject FromObject(object o)
public static new JObject FromObject(object o)
{
JToken token = FromObjectInternal(o);
+44 -4
View File
@@ -54,7 +54,7 @@ namespace Newtonsoft.Json.Linq
/// Gets or sets the property value.
/// </summary>
/// <value>The property value.</value>
public JToken Value
public new JToken Value
{
[DebuggerStepThrough]
get { return Last; }
@@ -107,13 +107,26 @@ namespace Newtonsoft.Json.Linq
/// Initializes a new instance of the <see cref="JProperty"/> class.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
public JProperty(string name, object value)
/// <param name="content">The property content.</param>
public JProperty(string name, params object[] content)
: this(name, (object)content)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JProperty"/> class.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="content">The property content.</param>
public JProperty(string name, object content)
{
ValidationUtils.ArgumentNotNull(name, "name");
_name = name;
Value = CreateFromContent(value);
Value = IsMultiContent(content)
? new JArray(content)
: CreateFromContent(content);
}
internal override void ValidateObject(JToken o, JToken previous)
@@ -154,5 +167,32 @@ namespace Newtonsoft.Json.Linq
{
return _name.GetHashCode() ^ ((Value != null) ? Value.GetDeepHashCode() : 0);
}
/// <summary>
/// Loads an <see cref="JProperty"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param>
/// <returns>A <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static JProperty Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JProperty from JsonReader.");
}
if (reader.TokenType != JsonToken.PropertyName)
throw new Exception(
"Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
JProperty p = new JProperty((string)reader.Value);
if (!reader.Read())
throw new Exception("Error reading JProperty from JsonReader.");
p.ReadContentFrom(reader);
return p;
}
}
}
+62 -1
View File
@@ -146,7 +146,7 @@ namespace Newtonsoft.Json.Linq
if (_parent == null)
return null;
JToken parentNext = ((JToken)_parent.Content)._next;
JToken parentNext = _parent.Content._next;
JToken parentNextBefore = null;
while (parentNext != this)
{
@@ -736,5 +736,66 @@ namespace Newtonsoft.Json.Linq
{
get { return this[key]; }
}
public JsonReader CreateReader()
{
return new JsonTokenReader(this);
}
internal static JToken FromObjectInternal(object o)
{
ValidationUtils.ArgumentNotNull(o, "o");
JsonSerializer jsonSerializer = new JsonSerializer();
JToken token;
using (JsonTokenWriter jsonWriter = new JsonTokenWriter())
{
jsonSerializer.Serialize(jsonWriter, o);
token = jsonWriter.Token;
}
return token;
}
/// <summary>
/// Creates a <see cref="JToken"/> from an object.
/// </summary>
/// <param name="o">The object that will be used to create <see cref="JToken"/>.</param>
/// <returns>A <see cref="JToken"/> with the value of the specified object</returns>
public static JToken FromObject(object o)
{
return FromObjectInternal(o);
}
public static JToken ReadFrom(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JToken from JsonReader.");
}
if (reader.TokenType == JsonToken.StartObject)
return JObject.Load(reader);
if (reader.TokenType == JsonToken.StartArray)
return JArray.Load(reader);
if (reader.TokenType == JsonToken.PropertyName)
return JProperty.Load(reader);
if (reader.TokenType == JsonToken.StartConstructor)
return JConstructor.Load(reader);
// hack. change to look at TokenType rather than using value
if (!JsonReader.IsStartToken(reader.TokenType))
return new JValue(reader.Value);
// TODO: loading constructor and parameters?
throw new Exception("Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
public class JsonTokenReader : JsonReader
{
private JToken _root;
private readonly JToken _root;
private JToken _parent;
private JToken _current;
+20 -5
View File
@@ -13,14 +13,22 @@ namespace Newtonsoft.Json.Linq
{
private JContainer _token;
private JContainer _parent;
// used when writer is writing single value and the value has no containing parent
private JValue _value;
/// <summary>
/// Gets the token being writen.
/// </summary>
/// <value>The token being writen.</value>
public JContainer Token
public JToken Token
{
get { return _token; }
get
{
if (_token != null)
return _token;
return _value;
}
}
/// <summary>
@@ -133,10 +141,17 @@ namespace Newtonsoft.Json.Linq
private void AddValue(JValue value, JsonToken token)
{
_parent.Add(value);
if (_parent != null)
{
_parent.Add(value);
if (_parent.Type == JsonTokenType.Property)
_parent = _parent.Parent;
if (_parent.Type == JsonTokenType.Property)
_parent = _parent.Parent;
}
else
{
_value = value;
}
}
#region WriteValue methods
@@ -55,60 +55,83 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\HtmlColorConverter.cs" />
<Compile Include="DateTimeOffset.cs" />
<Compile Include="JsonArrayAttribute.cs" />
<Compile Include="JsonContainerAttribute.cs" />
<Compile Include="DefaultValueHandling.cs" />
<Compile Include="JsonConverterAttribute.cs" />
<Compile Include="JsonObjectAttribute.cs" />
<Compile Include="JsonSerializerSettings.cs" />
<Compile Include="JsonValidatingReader.cs" />
<Compile Include="Linq\IJEnumerable.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
<Compile Include="MemberSerialization.cs" />
<Compile Include="ObjectCreationHandling.cs" />
<Compile Include="Converters\IsoDateTimeConverter.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverter.cs" />
<Compile Include="Converters\JsonDateTimeSerializationMode.cs" />
<Compile Include="Converters\XmlNodeConverter.cs" />
<Compile Include="DateTimeOffset.cs" />
<Compile Include="DefaultValueHandling.cs" />
<Compile Include="JsonConvert.cs" />
<Compile Include="JsonConverter.cs" />
<Compile Include="JsonConverterAttribute.cs" />
<Compile Include="JsonConverterCollection.cs" />
<Compile Include="JsonIgnoreAttribute.cs" />
<Compile Include="JsonObjectAttribute.cs" />
<Compile Include="Converters\HtmlColorConverter.cs" />
<Compile Include="JsonTextReader.cs" />
<Compile Include="JsonPropertyAttribute.cs" />
<Compile Include="JsonRaw.cs" />
<Compile Include="JsonReader.cs" />
<Compile Include="JsonIgnoreAttribute.cs" />
<Compile Include="JsonTextWriter.cs" />
<Compile Include="JsonWriterException.cs" />
<Compile Include="JsonReaderException.cs" />
<Compile Include="JsonRaw.cs" />
<Compile Include="JsonConverter.cs" />
<Compile Include="JsonConverterCollection.cs" />
<Compile Include="JsonReader.cs" />
<Compile Include="JsonConvert.cs" />
<Compile Include="JsonSerializationException.cs" />
<Compile Include="JsonSerializer.cs" />
<Compile Include="JsonSerializerSettings.cs" />
<Compile Include="JsonTextReader.cs" />
<Compile Include="JsonTextWriter.cs" />
<Compile Include="JsonToken.cs" />
<Compile Include="JsonWriter.cs" />
<Compile Include="JsonWriterException.cs" />
<Compile Include="Linq\Extensions.cs" />
<Compile Include="Linq\IJEnumerable.cs" />
<Compile Include="Linq\JArray.cs" />
<Compile Include="Linq\JConstructor.cs" />
<Compile Include="Linq\JContainer.cs" />
<Compile Include="Linq\JEnumerable.cs" />
<Compile Include="Linq\JObject.cs" />
<Compile Include="Linq\JProperty.cs" />
<Compile Include="Linq\JArray.cs" />
<Compile Include="Linq\JsonTokenReader.cs" />
<Compile Include="Linq\JsonTokenType.cs" />
<Compile Include="Linq\JsonTokenWriter.cs" />
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
<Compile Include="Linq\JProperty.cs" />
<Compile Include="Linq\JsonTokenType.cs" />
<Compile Include="Linq\JValue.cs" />
<Compile Include="MemberMapping.cs" />
<Compile Include="MemberMappingCollection.cs" />
<Compile Include="MemberSerialization.cs" />
<Compile Include="Schema\Extensions.cs" />
<Compile Include="Schema\JsonSchemaException.cs" />
<Compile Include="Schema\JsonSchemaModel.cs" />
<Compile Include="Schema\JsonSchemaModelBuilder.cs" />
<Compile Include="Schema\JsonSchemaNodeCollection.cs" />
<Compile Include="Schema\JsonSchemaNode.cs" />
<Compile Include="Schema\JsonSchemaWriter.cs" />
<Compile Include="Schema\UndefinedSchemaIdHandling.cs" />
<Compile Include="Schema\ValidationEventArgs.cs" />
<Compile Include="Schema\ValidationEventHandler.cs" />
<Compile Include="Serialization\JsonMemberMapping.cs" />
<Compile Include="Serialization\JsonMemberMappingCollection.cs" />
<Compile Include="MissingMemberHandling.cs" />
<Compile Include="NullValueHandling.cs" />
<Compile Include="ObjectCreationHandling.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReferenceLoopHandling.cs" />
<Compile Include="StringBuffer.cs" />
<Compile Include="Utilities\CollectionUtils.cs" />
<Compile Include="Utilities\CollectionWrapper.cs" />
<Compile Include="Schema\JsonSchema.cs" />
<Compile Include="Schema\JsonSchemaBuilder.cs" />
<Compile Include="Schema\JsonSchemaConstants.cs" />
<Compile Include="Schema\JsonSchemaGenerator.cs" />
<Compile Include="Schema\JsonSchemaResolver.cs" />
<Compile Include="Schema\JsonSchemaType.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Utilities\ConvertUtils.cs" />
<Compile Include="Utilities\CollectionWrapper.cs" />
<Compile Include="Utilities\DateTimeUtils.cs" />
<Compile Include="Utilities\DictionaryWrapper.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="JsonToken.cs" />
<Compile Include="JsonWriter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringBuffer.cs" />
<Compile Include="Utilities\CollectionUtils.cs" />
<Compile Include="Utilities\ListWrapper.cs" />
<Compile Include="Utilities\MathUtils.cs" />
<Compile Include="Utilities\MiscellaneousUtils.cs" />
@@ -53,7 +53,10 @@
<Compile Include="Converters\JsonDateTimeSerializationMode.cs" />
<Compile Include="Converters\XmlNodeConverter.cs" />
<Compile Include="Converters\HtmlColorConverter.cs" />
<Compile Include="DateTimeOffset.cs" />
<Compile Include="DefaultValueHandling.cs" />
<Compile Include="JsonArrayAttribute.cs" />
<Compile Include="JsonContainerAttribute.cs" />
<Compile Include="JsonConvert.cs" />
<Compile Include="JsonConverter.cs" />
<Compile Include="JsonConverterAttribute.cs" />
@@ -70,6 +73,7 @@
<Compile Include="JsonTextReader.cs" />
<Compile Include="JsonTextWriter.cs" />
<Compile Include="JsonToken.cs" />
<Compile Include="JsonValidatingReader.cs" />
<Compile Include="JsonWriter.cs" />
<Compile Include="JsonWriterException.cs" />
<Compile Include="Linq\Extensions.cs" />
@@ -86,8 +90,6 @@
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
<Compile Include="Linq\JValue.cs" />
<Compile Include="MemberMapping.cs" />
<Compile Include="MemberMappingCollection.cs" />
<Compile Include="MemberSerialization.cs" />
<Compile Include="MissingMemberHandling.cs" />
<Compile Include="NullValueHandling.cs" />
@@ -100,6 +102,9 @@
<Compile Include="Utilities\ConvertUtils.cs" />
<Compile Include="Utilities\DateTimeUtils.cs" />
<Compile Include="Utilities\DictionaryWrapper.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\ListWrapper.cs" />
<Compile Include="Utilities\MathUtils.cs" />
@@ -107,6 +112,25 @@
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringUtils.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
<Compile Include="Schema\Extensions.cs" />
<Compile Include="Schema\JsonSchemaException.cs" />
<Compile Include="Schema\JsonSchemaModel.cs" />
<Compile Include="Schema\JsonSchemaModelBuilder.cs" />
<Compile Include="Schema\JsonSchemaNodeCollection.cs" />
<Compile Include="Schema\JsonSchemaNode.cs" />
<Compile Include="Schema\JsonSchemaWriter.cs" />
<Compile Include="Schema\UndefinedSchemaIdHandling.cs" />
<Compile Include="Schema\ValidationEventArgs.cs" />
<Compile Include="Schema\ValidationEventHandler.cs" />
<Compile Include="Schema\JsonSchema.cs" />
<Compile Include="Schema\JsonSchemaBuilder.cs" />
<Compile Include="Schema\JsonSchemaConstants.cs" />
<Compile Include="Schema\JsonSchemaGenerator.cs" />
<Compile Include="Schema\JsonSchemaResolver.cs" />
<Compile Include="Schema\JsonSchemaType.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\JsonMemberMapping.cs" />
<Compile Include="Serialization\JsonMemberMappingCollection.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight\v2.0\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+25 -2
View File
@@ -74,10 +74,13 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="JsonArrayAttribute.cs" />
<Compile Include="JsonContainerAttribute.cs" />
<Compile Include="DefaultValueHandling.cs" />
<Compile Include="JsonConverterAttribute.cs" />
<Compile Include="JsonObjectAttribute.cs" />
<Compile Include="JsonSerializerSettings.cs" />
<Compile Include="JsonValidatingReader.cs" />
<Compile Include="Linq\IJEnumerable.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
<Compile Include="MemberSerialization.cs" />
@@ -112,15 +115,35 @@
<Compile Include="Linq\JProperty.cs" />
<Compile Include="Linq\JsonTokenType.cs" />
<Compile Include="Linq\JValue.cs" />
<Compile Include="MemberMapping.cs" />
<Compile Include="MemberMappingCollection.cs" />
<Compile Include="Schema\Extensions.cs" />
<Compile Include="Schema\JsonSchemaException.cs" />
<Compile Include="Schema\JsonSchemaModel.cs" />
<Compile Include="Schema\JsonSchemaModelBuilder.cs" />
<Compile Include="Schema\JsonSchemaNodeCollection.cs" />
<Compile Include="Schema\JsonSchemaNode.cs" />
<Compile Include="Schema\JsonSchemaWriter.cs" />
<Compile Include="Schema\UndefinedSchemaIdHandling.cs" />
<Compile Include="Schema\ValidationEventArgs.cs" />
<Compile Include="Schema\ValidationEventHandler.cs" />
<Compile Include="Serialization\JsonMemberMapping.cs" />
<Compile Include="Serialization\JsonMemberMappingCollection.cs" />
<Compile Include="MissingMemberHandling.cs" />
<Compile Include="NullValueHandling.cs" />
<Compile Include="ReferenceLoopHandling.cs" />
<Compile Include="Schema\JsonSchema.cs" />
<Compile Include="Schema\JsonSchemaBuilder.cs" />
<Compile Include="Schema\JsonSchemaConstants.cs" />
<Compile Include="Schema\JsonSchemaGenerator.cs" />
<Compile Include="Schema\JsonSchemaResolver.cs" />
<Compile Include="Schema\JsonSchemaType.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Utilities\ConvertUtils.cs" />
<Compile Include="Utilities\CollectionWrapper.cs" />
<Compile Include="Utilities\DateTimeUtils.cs" />
<Compile Include="Utilities\DictionaryWrapper.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="JsonToken.cs" />
<Compile Include="JsonWriter.cs" />
+66
View File
@@ -0,0 +1,66 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
public static class Extensions
{
public static bool IsValid(this JToken source, JsonSchema schema)
{
bool valid = true;
source.Validate(schema, (sender, args) => { valid = false; });
return valid;
}
public static void Validate(this JToken source, JsonSchema schema)
{
source.Validate(schema, null);
}
public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler)
{
ValidationUtils.ArgumentNotNull(source, "source");
ValidationUtils.ArgumentNotNull(schema, "schema");
using (JsonValidatingReader reader = new JsonValidatingReader(source.CreateReader()))
{
reader.Schema = schema;
if (validationEventHandler != null)
reader.ValidationEventHandler += validationEventHandler;
while (reader.Read())
{
}
}
}
}
}
+134
View File
@@ -0,0 +1,134 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Schema
{
public class JsonSchema
{
public string Id { get; set; }
public string Title { get; set; }
public bool? Optional { get; set; }
public bool? ReadOnly { get; set; }
public bool? Hidden { get; set; }
public bool? Transient { get; set; }
public string Description { get; set; }
public JsonSchemaType? Type { get; set; }
public string Pattern { get; set; }
public int? MinimumLength { get; set; }
public int? MaximumLength { get; set; }
public int? MaximumDecimals { get; set; }
public double? Minimum { get; set; }
public double? Maximum { get; set; }
public int? MinimumItems { get; set; }
public int? MaximumItems { get; set; }
public IList<JsonSchema> Items { get; set; }
public IDictionary<string, JsonSchema> Properties { get; set; }
public JsonSchema AdditionalProperties { get; set; }
public bool AllowAdditionalProperties { get; set; }
public string Requires { get; set; }
public IList<string> Identity { get; set; }
public IList<JToken> Enum { get; set; }
public IDictionary<JToken, string> Options { get; set; }
public JsonSchemaType? Disallow { get; set; }
public JToken Default { get; set; }
public JsonSchema Extends { get; set; }
public string Format { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
internal string InternalId
{
get { return _internalId; }
}
public JsonSchema()
{
AllowAdditionalProperties = true;
}
public static JsonSchema Read(JsonReader reader)
{
return Read(reader, new JsonSchemaResolver());
}
public static JsonSchema Read(JsonReader reader, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
return builder.Parse(reader);
}
public static JsonSchema Parse(string json)
{
return Parse(json, new JsonSchemaResolver());
}
public static JsonSchema Parse(string json, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(json, "json");
JsonReader reader = new JsonTextReader(new StringReader(json));
return Read(reader, resolver);
}
public void WriteTo(JsonWriter writer)
{
WriteTo(writer, new JsonSchemaResolver());
}
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver);
schemaWriter.WriteSchema(this);
}
public override string ToString()
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
WriteTo(jsonWriter);
return writer.ToString();
}
}
}
@@ -0,0 +1,393 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaBuilder
{
private JsonReader _reader;
private readonly IList<JsonSchema> _stack;
private readonly JsonSchemaResolver _resolver;
private JsonSchema _currentSchema;
private void Push(JsonSchema value)
{
_currentSchema = value;
_stack.Add(value);
_resolver.LoadedSchemas.Add(value);
}
private JsonSchema Pop()
{
JsonSchema poppedSchema = _currentSchema;
_stack.RemoveAt(_stack.Count - 1);
_currentSchema = _stack.LastOrDefault();
return poppedSchema;
}
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
public JsonSchemaBuilder(JsonSchemaResolver resolver)
{
_stack = new List<JsonSchema>();
_resolver = resolver;
}
internal JsonSchema Parse(JsonReader reader)
{
_reader = reader;
if (reader.TokenType == JsonToken.None)
_reader.Read();
return BuildSchema();
}
private JsonSchema BuildSchema()
{
if (_reader.TokenType != JsonToken.StartObject)
throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
_reader.Read();
// empty schema object
if (_reader.TokenType == JsonToken.EndObject)
{
Push(new JsonSchema());
return Pop();
}
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
// schema reference
if (propertyName == JsonSchemaConstants.ReferencePropertyName)
{
string id = (string)_reader.Value;
_reader.Read();
JsonSchema referencedSchema = _resolver.GetSchema(id);
if (referencedSchema == null)
throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
return referencedSchema;
}
// regular ol' schema object
Push(new JsonSchema());
ProcessSchemaProperty(propertyName);
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{
propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
ProcessSchemaProperty(propertyName);
}
return Pop();
}
private void ProcessSchemaProperty(string propertyName)
{
switch (propertyName)
{
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.OptionalPropertyName:
CurrentSchema.Optional = (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.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.MaximumDecimalsPropertyName:
CurrentSchema.MaximumDecimals = Convert.ToInt32(_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;
}
}
private void ProcessExtends()
{
CurrentSchema.Extends = BuildSchema();
}
private void ProcessEnum()
{
if (_reader.TokenType != JsonToken.StartArray)
throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
CurrentSchema.Enum = new List<JToken>();
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{
JToken value = JToken.ReadFrom(_reader);
CurrentSchema.Enum.Add(value);
}
}
private void ProcessOptions()
{
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 new Exception("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 new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
}
if (value == null)
throw new Exception("No value specified for JSON schema option.");
if (CurrentSchema.Options.ContainsKey(value))
throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
CurrentSchema.Options.Add(value, label);
}
break;
default:
throw new Exception("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 new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
CurrentSchema.Identity.Add(_reader.Value.ToString());
}
break;
default:
throw new Exception("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;
else
CurrentSchema.AdditionalProperties = BuildSchema();
}
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 new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
}
}
private void ProcessProperties()
{
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
if (_reader.TokenType != JsonToken.StartObject)
throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
_reader.Read();
if (properties.ContainsKey(propertyName))
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
properties.Add(propertyName, BuildSchema());
}
CurrentSchema.Properties = properties;
}
private JsonSchemaType? ProcessType()
{
switch (_reader.TokenType)
{
case JsonToken.String:
return MapType(_reader.Value.ToString());
case JsonToken.StartArray:
// ensure type is in blank state before ORing values
JsonSchemaType? type = JsonSchemaType.None;
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{
if (_reader.TokenType != JsonToken.String)
throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
type = type | MapType(_reader.Value.ToString());
}
return type;
default:
throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
}
}
internal static JsonSchemaType MapType(string type)
{
JsonSchemaType mappedType;
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
return mappedType;
}
internal static string MapType(JsonSchemaType type)
{
return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;
}
}
}
@@ -0,0 +1,80 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Schema
{
internal static class JsonSchemaConstants
{
public const string TypePropertyName = "type";
public const string PropertiesPropertyName = "properties";
public const string ItemsPropertyName = "items";
public const string OptionalPropertyName = "optional";
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 MinimumItemsPropertyName = "minItems";
public const string MaximumItemsPropertyName = "maxItems";
public const string PatternPropertyName = "pattern";
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";
public const string FormatPropertyName = "format";
public const string DefaultPropertyName = "default";
public const string TransientPropertyName = "transient";
public const string MaximumDecimalsPropertyName = "maxDecimal";
public const string HiddenPropertyName = "hidden";
public const string DisallowPropertyName = "disallow";
public const string ExtendsPropertyName = "extends";
public const string IdPropertyName = "id";
public const string OptionValuePropertyName = "value";
public const string OptionLabelPropertyName = "label";
public const string ReferencePropertyName = "$ref";
public static readonly IDictionary<string, JsonSchemaType> JsonSchemaTypeMapping = new Dictionary<string, JsonSchemaType>()
{
{"string", JsonSchemaType.String},
{"object", JsonSchemaType.Object},
{"integer", JsonSchemaType.Integer},
{"number", JsonSchemaType.Float},
{"null", JsonSchemaType.Null},
{"boolean", JsonSchemaType.Boolean},
{"array", JsonSchemaType.Array},
{"any", JsonSchemaType.Any}
};
}
}
@@ -0,0 +1,63 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// Returns detailed information about the schema exception.
/// </summary>
public class JsonSchemaException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class.
/// </summary>
public JsonSchemaException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonSchemaException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public JsonSchemaException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
@@ -0,0 +1,334 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
namespace Newtonsoft.Json.Schema
{
public class JsonSchemaGenerator
{
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private Type _currentType;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private Type CurrentType
{
get { return _currentType; }
}
private void Push(TypeSchema typeSchema)
{
_currentType = typeSchema.Type;
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentType = newValue.Type;
_currentSchema = newValue.Schema;
}
else
{
_currentType = null;
_currentSchema = null;
}
return popped;
}
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, !rootSchemaNullable);
}
public string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
public string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !PocketPC
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, bool valueRequired)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
return resolvedSchema;
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (CollectionUtils.IsDictionaryType(type))
{
// TODO: include null
CurrentSchema.Type = JsonSchemaType.Object;
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
// can be converted to a string
if (typeof (IConvertible).IsAssignableFrom(keyType))
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, false);
}
}
}
else if (CollectionUtils.IsCollectionType(type))
{
// TODO: include null
CurrentSchema.Type = JsonSchemaType.Array;
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : false;
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, !allowNullItem));
}
}
else
{
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (HasFlag(CurrentSchema.Type, JsonSchemaType.Object))
{
CurrentSchema.Id = GetTypeId(type, false);
JsonMemberMappingCollection mappings = JsonTypeReflector.GetMemberMappings(type);
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonMemberMapping mapping in mappings)
{
if (!mapping.Ignored)
{
Type propertyMemberType = ReflectionUtils.GetMemberUnderlyingType(mapping.Member);
JsonSchema propertySchema = GenerateInternal(propertyMemberType, mapping.Required);
if (mapping.DefaultValue != null)
propertySchema.Default = JToken.FromObject(mapping.DefaultValue);
CurrentSchema.Properties.Add(mapping.MappingName, propertySchema);
}
}
}
else if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum)
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<ulong> enumValues = EnumUtils.GetNamesAndValues<ulong>(type);
foreach (EnumValue<ulong> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
}
return Pop().Schema;
}
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
return ((value & flag) == flag);
}
private JsonSchemaType GetJsonSchemaType(Type type, bool valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (!valueRequired && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Empty:
case TypeCode.Object:
if (ConvertUtils.CanConvertType(type, typeof(string), false))
return schemaType | JsonSchemaType.String;
return schemaType | JsonSchemaType.Object;
case TypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
case TypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case TypeCode.Char:
return schemaType | JsonSchemaType.String;
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return schemaType | JsonSchemaType.Integer;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case TypeCode.DateTime:
return schemaType | JsonSchemaType.String;
case TypeCode.String:
return schemaType | JsonSchemaType.String;
default:
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
@@ -0,0 +1,103 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaModel
{
public bool Optional { get; set; }
public JsonSchemaType Type { get; set; }
public int? MinimumLength { get; set; }
public int? MaximumLength { get; set; }
public int? MaximumDecimals { get; set; }
public double? Minimum { get; set; }
public double? Maximum { get; set; }
public int? MinimumItems { get; set; }
public int? MaximumItems { get; set; }
public IList<string> Patterns { get; set; }
public IList<JsonSchemaModel> Items { get; set; }
public IDictionary<string, JsonSchemaModel> Properties { get; set; }
public JsonSchemaModel AdditionalProperties { get; set; }
public bool AllowAdditionalProperties { get; set; }
public IList<JToken> Enum { get; set; }
public JsonSchemaType Disallow { get; set; }
public JsonSchemaModel()
{
Type = JsonSchemaType.Any;
AllowAdditionalProperties = true;
Optional = true;
}
public static JsonSchemaModel Create(IList<JsonSchema> schemata)
{
JsonSchemaModel model = new JsonSchemaModel();
foreach (JsonSchema schema in schemata)
{
Combine(model, schema);
}
return model;
}
private static void Combine(JsonSchemaModel model, JsonSchema schema)
{
model.Optional = model.Optional && (schema.Optional ?? false);
model.Type = model.Type & (schema.Type ?? JsonSchemaType.Any);
model.MinimumLength = MathUtils.Max(model.MinimumLength, schema.MinimumLength);
model.MaximumLength = MathUtils.Min(model.MaximumLength, schema.MaximumLength);
model.MaximumDecimals = MathUtils.Min(model.MaximumDecimals, schema.MaximumDecimals);
model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum);
model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum);
model.MinimumItems = MathUtils.Max(model.MinimumItems, schema.MinimumItems);
model.MaximumItems = MathUtils.Min(model.MaximumItems, schema.MaximumItems);
model.AllowAdditionalProperties = model.AllowAdditionalProperties && schema.AllowAdditionalProperties;
if (schema.Enum != null)
{
if (model.Enum == null)
model.Enum = new List<JToken>();
model.Enum.AddRangeDistinct(schema.Enum, new JTokenEqualityComparer());
}
model.Disallow = model.Disallow | (schema.Disallow ?? JsonSchemaType.None);
if (schema.Pattern != null)
{
if (model.Patterns == null)
model.Patterns = new List<string>();
model.Patterns.AddDistinct(schema.Pattern);
}
}
}
}
@@ -0,0 +1,159 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaModelBuilder
{
private JsonSchemaNodeCollection _nodes = new JsonSchemaNodeCollection();
private Dictionary<JsonSchemaNode, JsonSchemaModel> _nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>();
private JsonSchemaNode _node ;
public JsonSchemaModel Build(JsonSchema schema)
{
_nodes = new JsonSchemaNodeCollection();
_node = AddSchema(null, schema);
_nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>();
JsonSchemaModel model = BuildNodeModel(_node);
return model;
}
public JsonSchemaNode AddSchema(JsonSchemaNode existingNode, JsonSchema schema)
{
string newId;
if (existingNode != null)
{
if (existingNode.Schemas.Contains(schema))
return existingNode;
newId = JsonSchemaNode.GetId(existingNode.Schemas.Union(new[] { schema }));
}
else
{
newId = JsonSchemaNode.GetId(new[] { schema });
}
if (_nodes.Contains(newId))
return _nodes[newId];
JsonSchemaNode currentNode = (existingNode != null)
? existingNode.Combine(schema)
: new JsonSchemaNode(schema);
_nodes.Add(currentNode);
if (schema.Properties != null)
{
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties)
{
AddProperty(currentNode, property.Key, property.Value);
}
}
if (schema.Items != null)
{
for (int i = 0; i < schema.Items.Count; i++)
{
AddItem(currentNode, i, schema.Items[i]);
}
}
if (schema.AdditionalProperties != null)
AddAdditionalProperties(currentNode, schema.AdditionalProperties);
if (schema.Extends != null)
currentNode = AddSchema(currentNode, schema.Extends);
return currentNode;
}
public void AddProperty(JsonSchemaNode parentNode, string propertyName, JsonSchema schema)
{
JsonSchemaNode propertyNode;
parentNode.Properties.TryGetValue(propertyName, out propertyNode);
parentNode.Properties[propertyName] = AddSchema(propertyNode, schema);
}
public void AddItem(JsonSchemaNode parentNode, int index, JsonSchema schema)
{
JsonSchemaNode existingItemNode = (parentNode.Items.Count > index)
? parentNode.Items[index]
: null;
JsonSchemaNode newItemNode = AddSchema(existingItemNode, schema);
if (!(parentNode.Items.Count > index))
{
parentNode.Items.Add(newItemNode);
}
else
{
parentNode.Items[index] = newItemNode;
}
}
public void AddAdditionalProperties(JsonSchemaNode parentNode, JsonSchema schema)
{
parentNode.AdditionalProperties = AddSchema(parentNode.AdditionalProperties, schema);
}
private JsonSchemaModel BuildNodeModel(JsonSchemaNode node)
{
JsonSchemaModel model;
if (_nodeModels.TryGetValue(node, out model))
return model;
model = JsonSchemaModel.Create(node.Schemas);
_nodeModels[node] = model;
foreach (KeyValuePair<string, JsonSchemaNode> property in node.Properties)
{
if (model.Properties == null)
model.Properties = new Dictionary<string, JsonSchemaModel>();
model.Properties[property.Key] = BuildNodeModel(property.Value);
}
for (int i = 0; i < node.Items.Count; i++)
{
if (model.Items == null)
model.Items = new List<JsonSchemaModel>();
model.Items.Add(BuildNodeModel(node.Items[i]));
}
if (node.AdditionalProperties != null)
model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties);
return model;
}
}
}
@@ -0,0 +1,70 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaNode
{
public string Id { get; private set; }
public ReadOnlyCollection<JsonSchema> Schemas { get; private set; }
public Dictionary<string, JsonSchemaNode> Properties { get; private set; }
public List<JsonSchemaNode> Items { get; private set; }
public JsonSchemaNode AdditionalProperties { get; set; }
public JsonSchemaNode(JsonSchema schema)
{
Schemas = new ReadOnlyCollection<JsonSchema>(new []{ schema });
Properties = new Dictionary<string, JsonSchemaNode>();
Items = new List<JsonSchemaNode>();
Id = GetId(Schemas);
}
private JsonSchemaNode(JsonSchemaNode source, JsonSchema schema)
{
Schemas = new ReadOnlyCollection<JsonSchema>(source.Schemas.Union(new[] { schema }).ToList());
Properties = new Dictionary<string, JsonSchemaNode>(source.Properties);
Items = new List<JsonSchemaNode>(source.Items);
AdditionalProperties = source.AdditionalProperties;
Id = GetId(Schemas);
}
public JsonSchemaNode Combine(JsonSchema schema)
{
return new JsonSchemaNode(this, schema);
}
public static string GetId(IEnumerable<JsonSchema> schemata)
{
return string.Join("-", schemata.Select(s => s.InternalId).OrderBy(id => id, StringComparer.Ordinal).ToArray());
}
}
}
@@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.ObjectModel;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaNodeCollection : KeyedCollection<string, JsonSchemaNode>
{
protected override string GetKeyForItem(JsonSchemaNode item)
{
return item.Id;
}
}
}
@@ -0,0 +1,51 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
public class JsonSchemaResolver
{
public IList<JsonSchema> LoadedSchemas { get; protected set; }
public JsonSchemaResolver()
{
LoadedSchemas = new List<JsonSchema>();
}
public virtual JsonSchema GetSchema(string id)
{
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => s.Id == id);
return schema;
}
}
}
@@ -0,0 +1,46 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Schema
{
[Flags]
public enum JsonSchemaType
{
None = 0,
String = 1,
Float = 2,
Integer = 4,
Boolean = 8,
Object = 16,
Array = 32,
Null = 64,
Any = String | Float | Integer | Boolean | Object | Array | Null
}
}
@@ -0,0 +1,213 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaWriter
{
private readonly JsonWriter _writer;
private readonly JsonSchemaResolver _resolver;
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
_writer = writer;
_resolver = resolver;
}
private void ReferenceOrWriteSchema(JsonSchema schema)
{
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
_writer.WriteValue(schema.Id);
_writer.WriteEndObject();
}
else
{
WriteSchema(schema);
}
}
public void WriteSchema(JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(schema, "schema");
if (!_resolver.LoadedSchemas.Contains(schema))
_resolver.LoadedSchemas.Add(schema);
_writer.WriteStartObject();
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.OptionalPropertyName, schema.Optional);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
if (schema.Type != null)
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
if (!schema.AllowAdditionalProperties)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
_writer.WriteValue(schema.AllowAdditionalProperties);
}
else
{
if (schema.AdditionalProperties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
if (schema.Properties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.PropertiesPropertyName);
_writer.WriteStartObject();
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties)
{
_writer.WritePropertyName(property.Key);
ReferenceOrWriteSchema(property.Value);
}
_writer.WriteEndObject();
}
WriteItems(schema);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumDecimalsPropertyName, schema.MaximumDecimals);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
if (schema.Enum != null)
{
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
_writer.WriteStartArray();
foreach (JToken token in schema.Enum)
{
token.WriteTo(_writer);
}
_writer.WriteEndArray();
}
if (schema.Default != null)
{
_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.OptionValuePropertyName);
_writer.WriteValue(option.Value);
}
_writer.WriteEndObject();
}
_writer.WriteEndArray();
}
if (schema.Disallow != null)
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
if (schema.Extends != null)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
ReferenceOrWriteSchema(schema.Extends);
}
_writer.WriteEndObject();
}
private void WriteItems(JsonSchema schema)
{
if (CollectionUtils.IsNullOrEmpty(schema.Items))
return;
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (schema.Items.Count == 1)
{
ReferenceOrWriteSchema(schema.Items[0]);
return;
}
_writer.WriteStartArray();
foreach (JsonSchema itemSchema in schema.Items)
{
ReferenceOrWriteSchema(itemSchema);
}
_writer.WriteEndArray();
}
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
{
IList<JsonSchemaType> types;
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
types = new List<JsonSchemaType> { type };
else
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
if (types.Count == 0)
return;
writer.WritePropertyName(propertyName);
if (types.Count == 1)
{
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
return;
}
writer.WriteStartArray();
foreach (JsonSchemaType jsonSchemaType in types)
{
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
}
writer.WriteEndArray();
}
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
{
if (value != null)
{
writer.WritePropertyName(propertyName);
writer.WriteValue(value);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More