From 68eacc480b484e6a3f0c9ccf921a06e1a679ff21 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Wed, 23 Jan 2013 21:39:54 +1300 Subject: [PATCH] -JSON Schema fixes -Fixed static values being included with fields serialization -Examples! (work in progress) --- Doc/ContractResolver.aml | 2 +- .../Converters/DataTableConverterTests.cs | 4 +- .../Examples/CustomContractResolver.cs | 68 ++++++++++++ .../Examples/DataContractAndDataMember.cs | 42 +++++++ .../Examples/DefaultValueAttributeIgnore.cs | 45 ++++++++ .../Examples/DefaultValueHandlingIgnore.cs | 41 +++++++ .../Examples/DeserializeAnonymousType.cs | 22 ++++ .../Examples/DeserializeCollection.cs | 20 ++++ .../DeserializeConstructorHandling.cs | 51 +++++++++ .../DeserializeCustomCreationConverter.cs | 53 +++++++++ .../Examples/DeserializeDictionary.cs | 26 +++++ .../Examples/DeserializeFromBson.cs | 34 ++++++ .../Examples/DeserializeFromBsonCollection.cs | 36 ++++++ .../DeserializeMissingMemberHandling.cs | 37 +++++++ .../Examples/DeserializeObject.cs | 36 ++++++ .../DeserializeWithJsonSerializerToFile.cs | 31 ++++++ .../Examples/ErrorHandlingEvent.cs | 45 ++++++++ .../Examples/JsonConverterAttributeClass.cs | 53 +++++++++ .../JsonConverterAttributeProperty.cs | 43 ++++++++ .../Examples/JsonObjectAttributeOptIn.cs | 41 +++++++ .../Examples/JsonPropertyItemLevelSetting.cs | 70 ++++++++++++ .../Examples/JsonPropertyName.cs | 36 ++++++ .../Examples/JsonPropertyOrder.cs | 53 +++++++++ .../JsonPropertyPropertyLevelSetting.cs | 36 ++++++ .../Examples/JsonPropertyRequired.cs | 35 ++++++ .../Documentation/Examples/Linq/Clone.cs | 46 ++++++++ .../Linq/CreateJsonAnonymousObject.cs | 77 +++++++++++++ .../Linq/CreateJsonCollectionInitializer.cs | 37 +++++++ .../Examples/Linq/CreateJsonDeclaratively.cs | 78 +++++++++++++ .../Examples/Linq/CreateJsonDynamic.cs | 35 ++++++ .../Examples/Linq/CreateJsonJTokenWriter.cs | 36 ++++++ .../Examples/Linq/CreateJsonManually.cs | 29 +++++ .../Examples/Linq/CreateReader.cs | 49 +++++++++ .../Examples/Linq/CreateWriter.cs | 37 +++++++ .../Documentation/Examples/Linq/DeepEquals.cs | 44 ++++++++ .../Examples/Linq/DeserializeWithLinq.cs | 52 +++++++++ .../Documentation/Examples/Linq/FromObject.cs | 66 +++++++++++ .../Examples/Linq/JObjectProperties.cs | 34 ++++++ .../Documentation/Examples/Linq/JValueCast.cs | 55 ++++++++++ .../Examples/Linq/JValueValue.cs | 28 +++++ .../Documentation/Examples/Linq/ModifyJson.cs | 53 +++++++++ .../Examples/Linq/ParseJsonAny.cs | 34 ++++++ .../Examples/Linq/ParseJsonArray.cs | 29 +++++ .../Examples/Linq/ParseJsonObject.cs | 33 ++++++ .../Examples/Linq/QueryJsonDynamic.cs | 44 ++++++++ .../Documentation/Examples/Linq/ReadJson.cs | 24 ++++ .../Examples/Linq/SerializeWithLinq.cs | 66 +++++++++++ .../Examples/Linq/ToObjectComplex.cs | 42 +++++++ .../Examples/Linq/ToObjectGeneric.cs | 31 ++++++ .../Examples/Linq/ToObjectType.cs | 31 ++++++ .../Documentation/Examples/Linq/ToString.cs | 30 +++++ .../Examples/Linq/ToStringJsonConverter.cs | 20 ++++ .../Examples/Linq/WriteToJsonFile.cs | 29 +++++ .../Examples/NullValueHandlingIgnore.cs | 48 ++++++++ .../Documentation/Examples/PopulateObject.cs | 51 +++++++++ .../Examples/PropertyJsonIgnore.cs | 33 ++++++ .../Examples/ReferenceLoopHandlingIgnore.cs | 37 +++++++ .../Examples/ReferenceLoopHandlingObject.cs | 98 +++++++++++++++++ .../SerializationCallbackAttributes.cs | 103 ++++++++++++++++++ .../Examples/SerializeCollection.cs | 25 +++++ .../Examples/SerializeContractResolver.cs | 43 ++++++++ .../Examples/SerializeDateFormatHandling.cs | 28 +++++ .../Examples/SerializeDateTimeZoneHandling.cs | 87 +++++++++++++++ .../Examples/SerializeDictionary.cs | 29 +++++ .../Documentation/Examples/SerializeObject.cs | 46 ++++++++ .../Examples/SerializeSerializationBinder.cs | 69 ++++++++++++ .../Documentation/Examples/SerializeToBson.cs | 45 ++++++++ .../Examples/SerializeTypeNameHandling.cs | 89 +++++++++++++++ .../Examples/SerializeUnindentedJson.cs | 38 +++++++ .../Examples/SerializeWithJsonConverters.cs | 35 ++++++ .../SerializeWithJsonSerializerToFile.cs | 37 +++++++ .../Documentation/Examples/TraceWriter.cs | 38 +++++++ .../Documentation/LinqToJsonTests.cs | 15 +++ Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs | 5 + .../Newtonsoft.Json.Tests.csproj | 71 ++++++++++++ .../Properties/AssemblyInfo.cs | 2 +- .../Schema/JsonSchemaBuilderTests.cs | 80 ++++++++++++++ .../Schema/JsonSchemaSpecTests.cs | 2 - .../Schema/JsonSchemaTests.cs | 84 ++++++++++++++ .../Serialization/JsonSerializerTest.cs | 102 +++++++++++++++++ Src/Newtonsoft.Json.Tests/TestFixtureBase.cs | 8 +- .../JsonSerializationException.cs | 2 +- Src/Newtonsoft.Json/Linq/JToken.cs | 84 +++++++------- .../Properties/AssemblyInfo.cs | 2 +- Src/Newtonsoft.Json/Schema/JsonSchema.cs | 2 +- .../Schema/JsonSchemaBuilder.cs | 2 +- .../Serialization/DefaultContractResolver.cs | 3 +- 87 files changed, 3519 insertions(+), 53 deletions(-) create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomContractResolver.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DataContractAndDataMember.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueAttributeIgnore.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueHandlingIgnore.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeAnonymousType.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCollection.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeConstructorHandling.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCustomCreationConverter.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeDictionary.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBson.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBsonCollection.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeMissingMemberHandling.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingEvent.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeClass.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeProperty.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonObjectAttributeOptIn.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyItemLevelSetting.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyName.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyOrder.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyPropertyLevelSetting.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyRequired.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/Clone.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonAnonymousObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonCollectionInitializer.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDeclaratively.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDynamic.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonJTokenWriter.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonManually.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateReader.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateWriter.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeepEquals.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeserializeWithLinq.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/FromObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JObjectProperties.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueCast.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueValue.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ModifyJson.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonAny.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonArray.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonDynamic.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJson.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/SerializeWithLinq.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectComplex.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectGeneric.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectType.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToString.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToStringJsonConverter.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteToJsonFile.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/NullValueHandlingIgnore.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/PopulateObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/PropertyJsonIgnore.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingIgnore.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializationCallbackAttributes.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeCollection.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeContractResolver.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateFormatHandling.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateTimeZoneHandling.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDictionary.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeObject.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeSerializationBinder.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeToBson.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeTypeNameHandling.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeUnindentedJson.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonConverters.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonSerializerToFile.cs create mode 100644 Src/Newtonsoft.Json.Tests/Documentation/Examples/TraceWriter.cs diff --git a/Doc/ContractResolver.aml b/Doc/ContractResolver.aml index db6ecf7e..2fdb0e1d 100644 --- a/Doc/ContractResolver.aml +++ b/Doc/ContractResolver.aml @@ -58,7 +58,7 @@ conditional serialization for a property ConditionalProperties.htm _self - using an IContractResolver. This is useful if you want to conditional serialize a property but don't want to add additional methods to your type. + using an IContractResolver. This is useful if you want to conditionally serialize a property but don't want to add additional methods to your type. diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs index 2e1b9e3b..f223a6cb 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs @@ -216,7 +216,7 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual("shoes", table.Rows[2]["item"]); Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01); Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01); - Assert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]); + CustomAssert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]); } [Test] @@ -232,7 +232,7 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual("shoes", table.Rows[2]["item"]); Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01); Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01); - Assert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]); + CustomAssert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomContractResolver.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomContractResolver.cs new file mode 100644 index 00000000..45bc99e0 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomContractResolver.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class CustomContractResolver + { + public class DynamicContractResolver : DefaultContractResolver + { + private readonly char _startingWithChar; + public DynamicContractResolver(char startingWithChar) + { + _startingWithChar = startingWithChar; + } + + protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) + { + IList properties = base.CreateProperties(type, memberSerialization); + + // only serializer properties that start with the specified character + properties = + properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList(); + + return properties; + } + } + + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + + public string FullName + { + get { return FirstName + " " + LastName; } + } + } + + public void Example() + { + Person person = new Person + { + FirstName = "Dennis", + LastName = "Deepwater-Diver" + }; + + string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented, + new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') }); + + Console.WriteLine(startingWithF); + // { + // "FirstName": "Dennis", + // "FullName": "Dennis Deepwater-Diver" + // } + + string startingWithL = JsonConvert.SerializeObject(person, Formatting.Indented, + new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('L') }); + + Console.WriteLine(startingWithL); + // { + // "LastName": "Deepwater-Diver" + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DataContractAndDataMember.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DataContractAndDataMember.cs new file mode 100644 index 00000000..e6a52ead --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DataContractAndDataMember.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DataContractAndDataMember + { + [DataContract] + public class File + { + // excluded from serialization + // does not have DataMemberAttribute + public Guid Id { get; set; } + + [DataMember] + public string Name { get; set; } + [DataMember] + public int Size { get; set; } + } + + public void Example() + { + File file = new File + { + Id = Guid.NewGuid(), + Name = "ImportantLegalDocuments.docx", + Size = 50*1024 + }; + + string json = JsonConvert.SerializeObject(file, Formatting.Indented); + + Console.WriteLine(json); + // { + // "Name": "ImportantLegalDocuments.docx", + // "Size": 51200 + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueAttributeIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueAttributeIgnore.cs new file mode 100644 index 00000000..adb25556 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueAttributeIgnore.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DefaultValueAttributeIgnore + { + public class Customer + { + public string FirstName { get; set; } + public string LastName { get; set; } + + [DefaultValue(" ")] + public string FullName + { + get { return FirstName + " " + LastName; } + } + } + + public void Example() + { + Customer customer = new Customer(); + + string jsonIncludeDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented); + + Console.WriteLine(jsonIncludeDefaultValues); + // { + // "FirstName": null, + // "LastName": null, + // "FullName": " " + // } + + string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented, new JsonSerializerSettings + { + DefaultValueHandling = DefaultValueHandling.Ignore + }); + + Console.WriteLine(jsonIgnoreDefaultValues); + // {} + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueHandlingIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueHandlingIgnore.cs new file mode 100644 index 00000000..c3712a21 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DefaultValueHandlingIgnore.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DefaultValueHandlingIgnore + { + public class Person + { + public string Name { get; set; } + public int Age { get; set; } + public Person Partner { get; set; } + public decimal? Salary { get; set; } + } + + public void Example() + { + Person person = new Person(); + + string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented); + + Console.WriteLine(jsonIncludeDefaultValues); + // { + // "Name": null, + // "Age": 0, + // "Partner": null, + // "Salary": null + // } + + string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings + { + DefaultValueHandling = DefaultValueHandling.Ignore + }); + + Console.WriteLine(jsonIgnoreDefaultValues); + // {} + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeAnonymousType.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeAnonymousType.cs new file mode 100644 index 00000000..024c91dc --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeAnonymousType.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeAnonymousType + { + public void Example() + { + string json = @"{""Name"":""James""}"; + + var customerDefinition = new {Name = ""}; + + var customer = JsonConvert.DeserializeAnonymousType(json, customerDefinition); + + Console.WriteLine(customer.Name); + // James + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCollection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCollection.cs new file mode 100644 index 00000000..70c3838a --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCollection.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeCollection + { + public void Example() + { + string json = @"[""Starcraft"",""Halo"",""Legend of Zelda""]"; + + List videogames = JsonConvert.DeserializeObject>(json); + + Console.WriteLine(string.Join(", ", videogames)); + // Starcraft, Halo, Legend of Zelda + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeConstructorHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeConstructorHandling.cs new file mode 100644 index 00000000..06c56430 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeConstructorHandling.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeConstructorHandling + { + public class Website + { + public string Url { get; set; } + + private Website() + { + } + + public Website(Website website) + { + if (website == null) + throw new ArgumentNullException("website"); + + Url = website.Url; + } + } + + public void Example() + { + string json = @"{""Url"":""http://www.google.com""}"; + + try + { + JsonConvert.DeserializeObject(json); + } + catch (TargetInvocationException) + { + // Value cannot be null. + // Parameter name: website + } + + Website website = JsonConvert.DeserializeObject(json, new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }); + + Console.WriteLine(website.Url); + // http://www.google.com + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCustomCreationConverter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCustomCreationConverter.cs new file mode 100644 index 00000000..7998ce2c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeCustomCreationConverter.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeCustomCreationConverter + { + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + public DateTime BirthDate { get; set; } + } + + public class Employee : Person + { + public string Department { get; set; } + public string JobTitle { get; set; } + } + + public class PersonConverter : CustomCreationConverter + { + public override Person Create(Type objectType) + { + return new Employee(); + } + } + + public void Example() + { + string json = @"{ + ""Department"": ""Furniture"", + ""JobTitle"": ""Carpenter"", + ""FirstName"": ""John"", + ""LastName"": ""Joinery"", + ""BirthDate"": ""1983-02-02T00:00:00"" + }"; + + Person person = JsonConvert.DeserializeObject(json, new PersonConverter()); + + Console.WriteLine(person.GetType().Name); + // Employee + + Employee employee = (Employee) person; + + Console.WriteLine(employee.JobTitle); + // Capenter + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeDictionary.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeDictionary.cs new file mode 100644 index 00000000..3999e705 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeDictionary.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeDictionary + { + public void Example() + { + string json = @"{ + ""href"": ""/account/login.aspx"", + ""target"": ""_blank"" + }"; + + Dictionary htmlAttributes = JsonConvert.DeserializeObject>(json); + + Console.WriteLine(htmlAttributes["href"]); + // /account/login.aspx + + Console.WriteLine(htmlAttributes["target"]); + // _blank + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBson.cs new file mode 100644 index 00000000..28131084 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBson.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Bson; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeFromBson + { + public class Event + { + public string Name { get; set; } + public DateTime StartDate { get; set; } + } + + public void Example() + { + byte[] data = Convert.FromBase64String("MAAAAAJOYW1lAA4AAABNb3ZpZSBwcmVtaWVyAAlTdGFydERhdGUAwOApYTwBAAAA"); + + MemoryStream ms = new MemoryStream(data); + using (BsonReader reader = new BsonReader(ms)) + { + JsonSerializer serializer = new JsonSerializer(); + + Event e = serializer.Deserialize(reader); + + Console.WriteLine(e.Name); + // Movie premier + } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBsonCollection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBsonCollection.cs new file mode 100644 index 00000000..548cb38e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeFromBsonCollection.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Bson; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeFromBsonCollection + { + public class Event + { + public string Name { get; set; } + public DateTime StartDate { get; set; } + } + + public void Example() + { + byte[] data = Convert.FromBase64String("awAAAAMwADAAAAACTmFtZQAOAAAATW92aWUgcHJlbWllcgAJU3RhcnREYXRlAMDgKWE8AQAAAAMxADAAAAACTmFtZQAOAAAATW92aWUgcHJlbWllcgAJU3RhcnREYXRlAMDgKWE8AQAAAAA="); + + MemoryStream ms = new MemoryStream(data); + using (BsonReader reader = new BsonReader(ms)) + { + reader.ReadRootValueAsArray = true; + + JsonSerializer serializer = new JsonSerializer(); + + IList events = serializer.Deserialize>(reader); + + Console.WriteLine(events.Count); + // 2 + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeMissingMemberHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeMissingMemberHandling.cs new file mode 100644 index 00000000..f8c4881a --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeMissingMemberHandling.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeMissingMemberHandling + { + public class Account + { + public string FullName { get; set; } + public bool Deleted { get; set; } + } + + public void Example() + { + string json = @"{ + ""FullName"": ""Dan Deleted"", + ""Deleted"": true, + ""DeletedDate"": ""2013-01-20T00:00:00"" + }"; + + try + { + JsonConvert.DeserializeObject(json, new JsonSerializerSettings + { + MissingMemberHandling = MissingMemberHandling.Error + }); + } + catch (JsonSerializationException) + { + // Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23. + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeObject.cs new file mode 100644 index 00000000..76930aae --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeObject.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeObject + { + public class Account + { + public string Email { get; set; } + public bool Active { get; set; } + public DateTime CreatedDate { get; set; } + public IList Roles { get; set; } + } + + public void Example() + { + string json = @"{ + ""Email"": ""james@example.com"", + ""Active"": true, + ""CreatedDate"": ""2013-01-20T00:00:00Z"", + ""Roles"": [ + ""User"", + ""Admin"" + ] + }"; + + Account account = JsonConvert.DeserializeObject(json); + + Console.WriteLine(account.Email); + // james@example.com + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs new file mode 100644 index 00000000..4a65b7d8 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using File = System.IO.File; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class DeserializeWithJsonSerializerToFile + { + public class Movie + { + public string Name { get; set; } + public int Year { get; set; } + } + + public void Example() + { + // read file into a string and deserialize JSON to a type + Movie movie1 = JsonConvert.DeserializeObject(File.ReadAllText(@"c:\movie.json")); + + // deserialize JSON directly from a file + using (StreamReader file = File.OpenText(@"c:\movie.json")) + { + JsonSerializer serializer = new JsonSerializer(); + Movie movie2 = (Movie)serializer.Deserialize(file, typeof (Movie)); + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingEvent.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingEvent.cs new file mode 100644 index 00000000..9b22c9d4 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingEvent.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ErrorHandlingEvent + { + public void Example() + { + List errors = new List(); + + List c = JsonConvert.DeserializeObject>(@"[ + '2009-09-09T00:00:00Z', + 'I am not a date and will error!', + [ + 1 + ], + '1977-02-20T00:00:00Z', + null, + '2000-12-01T00:00:00Z' + ]", + new JsonSerializerSettings + { + Error = delegate(object sender, ErrorEventArgs args) + { + errors.Add(args.ErrorContext.Error.Message); + args.ErrorContext.Handled = true; + }, + Converters = { new IsoDateTimeConverter() } + }); + + // 2009-09-09T00:00:00Z + // 1977-02-20T00:00:00Z + // 2000-12-01T00:00:00Z + + // The string was not recognized as a valid DateTime. There is a unknown word starting at index 0. + // Unexpected token parsing date. Expected String, got StartArray. + // Cannot convert null value to System.DateTime. + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeClass.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeClass.cs new file mode 100644 index 00000000..3d9d7c11 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeClass.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonConverterAttributeClass + { + public class UserConverter : JsonConverter + { + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + User user = (User) value; + + writer.WriteValue(user.UserName); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + User user = new User(); + user.UserName = (string)reader.Value; + + return user; + } + + public override bool CanConvert(Type objectType) + { + return objectType == typeof (User); + } + } + + [JsonConverter(typeof(UserConverter))] + public class User + { + public string UserName { get; set; } + } + + public void Example() + { + User user = new User + { + UserName = @"domain\username" + }; + + string json = JsonConvert.SerializeObject(user, Formatting.Indented); + + Console.WriteLine(json); + // "domain\\username" + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeProperty.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeProperty.cs new file mode 100644 index 00000000..542c03dd --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonConverterAttributeProperty.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonConverterAttributeProperty + { + public enum UserStatus + { + NotConfirmed, + Active, + Deleted + } + + public class User + { + public string UserName { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public UserStatus Status { get; set; } + } + + public void Example() + { + User user = new User + { + UserName = @"domain\username", + Status = UserStatus.Deleted + }; + + string json = JsonConvert.SerializeObject(user, Formatting.Indented); + + Console.WriteLine(json); + // { + // "UserName": "domain\\username", + // "Status": "Deleted" + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonObjectAttributeOptIn.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonObjectAttributeOptIn.cs new file mode 100644 index 00000000..45606c26 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonObjectAttributeOptIn.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonObjectAttributeOptIn + { + [JsonObject(MemberSerialization.OptIn)] + public class File + { + // excluded from serialization + // does not have JsonPropertyAttribute + public Guid Id { get; set; } + + [JsonProperty] + public string Name { get; set; } + [JsonProperty] + public int Size { get; set; } + } + + public void Example() + { + File file = new File + { + Id = Guid.NewGuid(), + Name = "ImportantLegalDocuments.docx", + Size = 50 * 1024 + }; + + string json = JsonConvert.SerializeObject(file, Formatting.Indented); + + Console.WriteLine(json); + // { + // "Name": "ImportantLegalDocuments.docx", + // "Size": 51200 + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyItemLevelSetting.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyItemLevelSetting.cs new file mode 100644 index 00000000..8d1c758a --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyItemLevelSetting.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonPropertyItemLevelSetting + { + public class Business + { + public string Name { get; set; } + + [JsonProperty(ItemIsReference = true)] + public IList Employees { get; set; } + } + + public class Employee + { + public string Name { get; set; } + + [JsonProperty(IsReference = true)] + public Employee Manager { get; set; } + } + + public void Example() + { + Employee manager = new Employee + { + Name = "George-Michael" + }; + Employee worker = new Employee + { + Name = "Mabae", + Manager = manager + }; + + Business business = new Business + { + Name = "Acme Ltd.", + Employees = new List + { + manager, + worker + } + }; + + string json = JsonConvert.SerializeObject(business, Formatting.Indented); + + Console.WriteLine(json); + // { + // "Name": "Acme Ltd.", + // "Employees": [ + // { + // "$id": "1", + // "Name": "George-Michael", + // "Manager": null + // }, + // { + // "$id": "2", + // "Name": "Mabae", + // "Manager": { + // "$ref": "1" + // } + // } + // ] + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyName.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyName.cs new file mode 100644 index 00000000..c22b07b3 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyName.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonPropertyName + { + public class Videogame + { + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("release_date")] + public DateTime ReleaseDate { get; set; } + } + + public void Example() + { + Videogame starcraft = new Videogame + { + Name = "Starcraft", + ReleaseDate = new DateTime(1998, 1, 1) + }; + + string json = JsonConvert.SerializeObject(starcraft, Formatting.Indented); + + Console.WriteLine(json); + // { + // "name": "Starcraft", + // "release_date": "1998-01-01T00:00:00" + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyOrder.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyOrder.cs new file mode 100644 index 00000000..530cda8f --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyOrder.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonPropertyOrder + { + public class Account + { + public string EmailAddress { get; set; } + + // appear last + [JsonProperty(Order = 1)] + public bool Deleted { get; set; } + [JsonProperty(Order = 2)] + public DateTime DeletedDate { get; set; } + + public DateTime CreatedDate { get; set; } + public DateTime UpdatedDate { get; set; } + + // appear first + [JsonProperty(Order = -2)] + public string FullName { get; set; } + } + + public void Example() + { + Account account = new Account + { + FullName = "Aaron Account", + EmailAddress = "aaron@example.com", + Deleted = true, + DeletedDate = new DateTime(2013, 1, 25), + UpdatedDate = new DateTime(2013, 1, 25), + CreatedDate = new DateTime(2010, 10, 1) + }; + + string json = JsonConvert.SerializeObject(account, Formatting.Indented); + + Console.WriteLine(json); + // { + // "FullName": "Aaron Account", + // "EmailAddress": "aaron@example.com", + // "CreatedDate": "2010-10-01T00:00:00", + // "UpdatedDate": "2013-01-25T00:00:00", + // "Deleted": true, + // "DeletedDate": "2013-01-25T00:00:00" + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyPropertyLevelSetting.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyPropertyLevelSetting.cs new file mode 100644 index 00000000..58809be4 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyPropertyLevelSetting.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonPropertyPropertyLevelSetting + { + public class Vessel + { + public string Name { get; set; } + public string Class { get; set; } + + [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] + public DateTime? LaunchDate { get; set; } + } + + public void Example() + { + Vessel vessel = new Vessel + { + Name = "Red October", + Class = "Typhoon" + }; + + string json = JsonConvert.SerializeObject(vessel, Formatting.Indented); + + Console.WriteLine(json); + // { + // "Name": "Red October", + // "Class": "Typhoon" + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyRequired.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyRequired.cs new file mode 100644 index 00000000..0e56b606 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/JsonPropertyRequired.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class JsonPropertyRequired + { + public class Videogame + { + [JsonProperty(Required = Required.Always)] + public string Name { get; set; } + + [JsonProperty(Required = Required.AllowNull)] + public DateTime? ReleaseDate { get; set; } + } + + public void Example() + { + string json = @"{ + ""Name"": ""Starcraft III"", + ""ReleaseDate"": null + }"; + + Videogame starcraft = JsonConvert.DeserializeObject(json); + + Console.WriteLine(starcraft.Name); + // Starcraft III + + Console.WriteLine(starcraft.ReleaseDate); + // null + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/Clone.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/Clone.cs new file mode 100644 index 00000000..859d068b --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/Clone.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class Clone + { + public void Example() + { + JObject o1 = new JObject + { + {"String", "A string!"}, + {"Items", new JArray(1, 2)} + }; + + Console.WriteLine(o1.ToString()); + // { + // "String": "A string!", + // "Items": [ + // 1, + // 2 + // ] + // } + + JObject o2 = (JObject) o1.DeepClone(); + + Console.WriteLine(o2.ToString()); + // { + // "String": "A string!", + // "Items": [ + // 1, + // 2 + // ] + // } + + Console.WriteLine(JToken.DeepEquals(o1, o2)); + // true + + Console.WriteLine(Object.ReferenceEquals(o1, o2)); + // false + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonAnonymousObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonAnonymousObject.cs new file mode 100644 index 00000000..d98fa25f --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonAnonymousObject.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateJsonAnonymousObject + { + public class Post + { + public string Title { get; set; } + public string Description { get; set; } + public string Link { get; set; } + public IList Categories { get; set; } + } + + public void Example() + { + List posts = new List + { + new Post + { + Title = "Episode VII", + Description = "Episode VII production", + Categories = new List + { + "episode-vii", + "movie" + }, + Link = "episode-vii-production.aspx" + } + }; + + JObject o = JObject.FromObject(new + { + channel = new + { + title = "Star Wars", + link = "http://www.starwars.com", + description = "Star Wars blog.", + item = + from p in posts + orderby p.Title + select new + { + title = p.Title, + description = p.Description, + link = p.Link, + category = p.Categories + } + } + }); + + Console.WriteLine(o.ToString()); + // { + // "channel": { + // "title": "Star Wars", + // "link": "http://www.starwars.com", + // "description": "Star Wars blog.", + // "item": [ + // { + // "title": "Episode VII", + // "description": "Episode VII production", + // "link": "episode-vii-production.aspx", + // "category": [ + // "episode-vii", + // "movie" + // ] + // } + // ] + // } + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonCollectionInitializer.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonCollectionInitializer.cs new file mode 100644 index 00000000..efbd8a68 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonCollectionInitializer.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateJsonCollectionInitializer + { + public void Example() + { + JObject o = new JObject + { + {"Cpu", "Intel"}, + {"Memory", 32}, + { + "Drives", new JArray + { + "DVD", + "SSD" + } + } + }; + + Console.WriteLine(o.ToString()); + // { + // "Cpu": "Intel", + // "Memory": 32, + // "Drives": [ + // "DVD", + // "SSD" + // ] + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDeclaratively.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDeclaratively.cs new file mode 100644 index 00000000..3a89641e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDeclaratively.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateJsonDeclaratively + { + public class Post + { + public string Title { get; set; } + public string Description { get; set; } + public string Link { get; set; } + public IList Categories { get; set; } + } + + private List GetPosts() + { + return null; + } + public void Example() + { + List posts = GetPosts(); + + JObject rss = + new JObject( + new JProperty("channel", + new JObject( + new JProperty("title", "James Newton-King"), + new JProperty("link", "http://james.newtonking.com"), + new JProperty("description", "James Newton-King's blog."), + new JProperty("item", + new JArray( + from p in posts + orderby p.Title + select new JObject( + new JProperty("title", p.Title), + new JProperty("description", p.Description), + new JProperty("link", p.Link), + new JProperty("category", + new JArray( + from c in p.Categories + select new JValue(c))))))))); + + Console.WriteLine(rss.ToString()); + + // { + // "channel": { + // "title": "James Newton-King", + // "link": "http://james.newtonking.com", + // "description": "James Newton-King's blog.", + // "item": [ + // { + // "title": "Json.NET 1.3 + New license + Now on CodePlex", + // "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex", + // "link": "http://james.newtonking.com/projects/json-net.aspx", + // "category": [ + // "Json.NET", + // "CodePlex" + // ] + // }, + // { + // "title": "LINQ to JSON beta", + // "description": "Annoucing LINQ to JSON", + // "link": "http://james.newtonking.com/projects/json-net.aspx", + // "category": [ + // "Json.NET", + // "LINQ" + // ] + // } + // ] + // } + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDynamic.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDynamic.cs new file mode 100644 index 00000000..3c27d888 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonDynamic.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateJsonDynamic + { + public void Example() + { + dynamic product = new JObject(); + product.ProductName = "Elbow Grease"; + product.Enabled = true; + product.Price = 4.90m; + product.StockCount = 9000; + product.StockValue = 44100; + product.Tags = new JArray("Real", "OnSale"); + + Console.WriteLine(product.ToString()); + // { + // "ProductName": "Elbow Grease", + // "Enabled": true, + // "Price": 4.90, + // "StockCount": 9000, + // "StockValue": 44100, + // "Tags": [ + // "Real", + // "OnSale" + // ] + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonJTokenWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonJTokenWriter.cs new file mode 100644 index 00000000..50e7bc3e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonJTokenWriter.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateJsonJTokenWriter + { + public void Example() + { + JTokenWriter writer = new JTokenWriter(); + writer.WriteStartObject(); + writer.WritePropertyName("name1"); + writer.WriteValue("value1"); + writer.WritePropertyName("name2"); + writer.WriteStartArray(); + writer.WriteValue(1); + writer.WriteValue(2); + writer.WriteEndArray(); + writer.WriteEndObject(); + + JObject o = (JObject)writer.Token; + + Console.WriteLine(o.ToString()); + // { + // "name1": "value1", + // "name2": [ + // 1, + // 2 + // ] + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonManually.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonManually.cs new file mode 100644 index 00000000..1d177fa8 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateJsonManually.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateJsonManually + { + public void Example() + { + JArray array = new JArray(); + JValue text = new JValue("Manual text"); + JValue date = new JValue(new DateTime(2000, 5, 23)); + + array.Add(text); + array.Add(date); + + string json = array.ToString(); + + Console.WriteLine(json); + // [ + // "Manual text", + // "2000-05-23T00:00:00" + // ] + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateReader.cs new file mode 100644 index 00000000..b5102bc6 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateReader.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateReader + { + public void Example() + { + JObject o = new JObject + { + {"Cpu", "Intel"}, + {"Memory", 32}, + { + "Drives", new JArray + { + "DVD", + "SSD" + } + } + }; + + JsonReader reader = o.CreateReader(); + while (reader.Read()) + { + Console.Write(reader.TokenType); + if (reader.Value != null) + Console.Write(" - " + reader.Value); + + Console.WriteLine(); + } + + // StartObject + // PropertyName - Cpu + // String - Intel + // PropertyName - Memory + // Integer - 32 + // PropertyName - Drives + // StartArray + // String - DVD + // String - SSD + // EndArray + // EndObject + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateWriter.cs new file mode 100644 index 00000000..13966d43 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/CreateWriter.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class CreateWriter + { + public void Example() + { + JObject o = new JObject + { + {"name1", "value1"}, + {"name2", "value2"} + }; + + JsonWriter writer = o.CreateWriter(); + writer.WritePropertyName("name3"); + writer.WriteStartArray(); + writer.WriteValue(1); + writer.WriteValue(2); + writer.WriteEndArray(); + + Console.WriteLine(o.ToString()); + // { + // "name1": "value1", + // "name2": "value2", + // "name3": [ + // 1, + // 2 + // ] + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeepEquals.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeepEquals.cs new file mode 100644 index 00000000..9d3385d5 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeepEquals.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class DeepEquals + { + public void Example() + { + JValue s1 = new JValue("A string"); + JValue s2 = new JValue("A string"); + JValue s3 = new JValue("A STRING"); + + Console.WriteLine(JToken.DeepEquals(s1, s2)); + // true + + Console.WriteLine(JToken.DeepEquals(s2, s3)); + // false + + JObject o1 = new JObject + { + {"Integer", 12345}, + {"String", "A string"}, + {"Items", new JArray(1, 2)} + }; + + JObject o2 = new JObject + { + {"Integer", 12345}, + {"String", "A string"}, + {"Items", new JArray(1, 2)} + }; + + Console.WriteLine(JToken.DeepEquals(o1, o2)); + // true + + Console.WriteLine(JToken.DeepEquals(s1, o1["String"])); + // true + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeserializeWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeserializeWithLinq.cs new file mode 100644 index 00000000..4d06860e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/DeserializeWithLinq.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class DeserializeWithLinq + { + public class BlogPost + { + public string Title { get; set; } + public string AuthorName { get; set; } + public string AuthorTwitter { get; set; } + public string Body { get; set; } + public DateTime PostedDate { get; set; } + } + + public void Example() + { + string json = @"[ + { + ""Title"": ""Json.NET is awesome!"", + ""Author"": { + ""Name"": ""James Newton-King"", + ""Twitter"": ""@JamesNK"", + ""Picture"": ""/jamesnk.png"" + }, + ""Date"": ""2013-01-23T19:30:00"", + ""BodyHtml"": ""<h3>Title!</h3>\r\n<p>Content!</p>"" + } + ]"; + + JArray blogPostArray = JArray.Parse(json); + + IList blogPosts = blogPostArray.Select(p => new BlogPost + { + Title = (string) p["Title"], + AuthorName = (string) p["Author"]["Name"], + AuthorTwitter = (string) p["Author"]["Twitter"], + PostedDate = (DateTime) p["Date"], + Body = HttpUtility.HtmlDecode((string) p["BodyHtml"]) + }).ToList(); + + Console.WriteLine(blogPosts[0].Body); + //

Title!

+ //

Content!

+ } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/FromObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/FromObject.cs new file mode 100644 index 00000000..003c39e7 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/FromObject.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class FromObject + { + public class Computer + { + public string Cpu { get; set; } + public int Memory { get; set; } + public IList Drives { get; set; } + } + + public void Example() + { + JValue i = (JValue)JToken.FromObject(12345); + + Console.WriteLine(i.Type); + // Integer + Console.WriteLine(i.ToString()); + // 12345 + + JValue s = (JValue)JToken.FromObject("A string"); + + Console.WriteLine(s.Type); + // String + Console.WriteLine(s.ToString()); + // A string + + Computer computer = new Computer + { + Cpu = "Intel", + Memory = 32, + Drives = new List + { + "DVD", + "SSD" + } + }; + + JObject o = (JObject)JToken.FromObject(computer); + + Console.WriteLine(o.ToString()); + // { + // "Cpu": "Intel", + // "Memory": 32, + // "Drives": [ + // "DVD", + // "SSD" + // ] + // } + + JArray a = (JArray)JToken.FromObject(computer.Drives); + + Console.WriteLine(a.ToString()); + // [ + // "DVD", + // "SSD" + // ] + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JObjectProperties.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JObjectProperties.cs new file mode 100644 index 00000000..f02ecae8 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JObjectProperties.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class JObjectProperties + { + public void Example() + { + JObject o = new JObject + { + { "name1", "value1" }, + { "name2", "value2"} + }; + + foreach (JProperty property in o.Properties()) + { + Console.WriteLine(property.Name + " - " + property.Value); + } + // name1 - value1 + // name2 - value2 + + foreach (KeyValuePair property in o) + { + Console.WriteLine(property.Key + " - " + property.Value); + } + // name1 - value1 + // name2 - value2 + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueCast.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueCast.cs new file mode 100644 index 00000000..bc4ac4a2 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueCast.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class JValueCast + { + public void Example() + { + JValue v1 = new JValue("1"); + int i = (int)v1; + + Console.WriteLine(i); + // 1 + + JValue v2 = new JValue(true); + bool b = (bool)v2; + + Console.WriteLine(b); + // true + + JValue v3 = new JValue("19.95"); + decimal d = (decimal)v3; + + Console.WriteLine(d); + // 19.95 + + JValue v4 = new JValue(new DateTime(2013, 1, 21)); + string s = (string)v4; + + Console.WriteLine(s); + // 01/21/2013 00:00:00 + + JValue v5 = new JValue("http://www.bing.com"); + Uri u = (Uri)v5; + + Console.WriteLine(u); + // http://www.bing.com/ + + JValue v6 = new JValue((object)null); + u = (Uri)v6; + + Console.WriteLine((u != null) ? u.ToString() : "{null}"); + // {null} + + DateTime? dt = (DateTime?)v6; + + Console.WriteLine((dt != null) ? dt.ToString() : "{null}"); + // {null} + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueValue.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueValue.cs new file mode 100644 index 00000000..e4581336 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/JValueValue.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class JValueValue + { + public void Example() + { + JValue s = new JValue("A string value"); + + Console.WriteLine(s.Value.GetType().Name); + // String + Console.WriteLine(s.Value); + // A string value + + JValue u = new JValue(new Uri("http://www.google.com/")); + + Console.WriteLine(u.Value.GetType().Name); + // Uri + Console.WriteLine(u.Value); + // http://www.google.com/ + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ModifyJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ModifyJson.cs new file mode 100644 index 00000000..0fa0ea98 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ModifyJson.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ModifyJson + { + public void Example() + { + string json = @"{ + ""channel"": { + ""title"": ""Star Wars"", + ""link"": ""http://www.starwars.com"", + ""description"": ""Star Wars blog."", + ""obsolete"": ""Obsolete value"", + ""item"": [] + } + }"; + + JObject rss = JObject.Parse(json); + + JObject channel = (JObject)rss["channel"]; + + channel["title"] = ((string)channel["title"]).ToUpper(); + channel["description"] = ((string)channel["description"]).ToUpper(); + + channel.Property("obsolete").Remove(); + + channel.Property("description").AddAfterSelf(new JProperty("new", "New value")); + + JArray item = (JArray) channel["item"]; + item.Add("Item 1"); + item.Add("Item 2"); + + Console.WriteLine(rss.ToString()); + // { + // "channel": { + // "title": "STAR WARS", + // "link": "http://www.starwars.com", + // "description": "STAR WARS BLOG.", + // "new": "New value", + // "item": [ + // "Item 1", + // "Item 2" + // ] + // } + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonAny.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonAny.cs new file mode 100644 index 00000000..55497b0d --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonAny.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ParseJsonAny + { + public void Example() + { + JToken t1 = JToken.Parse("{}"); + + Console.WriteLine(t1.Type); + // Object + + JToken t2 = JToken.Parse("[]"); + + Console.WriteLine(t2.Type); + // Array + + JToken t3 = JToken.Parse("null"); + + Console.WriteLine(t3.Type); + // Null + + JToken t4 = JToken.Parse(@"""A string!"""); + + Console.WriteLine(t4.Type); + // String + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonArray.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonArray.cs new file mode 100644 index 00000000..aafed9a2 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonArray.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ParseJsonArray + { + public void Example() + { + string json = @"[ + 'Small', + 'Medium', + 'Large' + ]"; + + JArray a = JArray.Parse(json); + + Console.WriteLine(a.ToString()); + // [ + // "Small", + // "Medium", + // "Large" + // ] + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonObject.cs new file mode 100644 index 00000000..241d9ecc --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ParseJsonObject.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ParseJsonObject + { + public void Example() + { + string json = @"{ + CPU: 'Intel', + Drives: [ + 'DVD read/writer', + '500 gigabyte hard drive' + ] + }"; + + JObject o = JObject.Parse(json); + + Console.WriteLine(o.ToString()); + // { + // "CPU": "Intel", + // "Drives": [ + // "DVD read/writer", + // "500 gigabyte hard drive" + // ] + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonDynamic.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonDynamic.cs new file mode 100644 index 00000000..eb6b2653 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonDynamic.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class QueryJsonDynamic + { + public void Example() + { + string json = @"[ + { + ""Title"": ""Json.NET is awesome!"", + ""Author"": { + ""Name"": ""James Newton-King"", + ""Twitter"": ""@JamesNK"", + ""Picture"": ""/jamesnk.png"" + }, + ""Date"": ""2013-01-23T19:30:00"", + ""BodyHtml"": ""<h3>Title!</h3>\r\n<p>Content!</p>"" + } + ]"; + + dynamic blogPosts = JArray.Parse(json); + + dynamic blogPost = blogPosts[0]; + + string title = blogPost.Title; + Console.WriteLine(title); + // Json.NET is awesome! + + string author = blogPost.Author.Name; + Console.WriteLine(author); + // James Newton-King + + DateTime postDate = blogPost.Date; + Console.WriteLine(postDate); + // 23/01/2013 7:30:00 p.m. + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJson.cs new file mode 100644 index 00000000..7f4cf294 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJson.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ReadJson + { + public void Example() + { + JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json")); + + // read JSON directly from a file + using (StreamReader file = File.OpenText(@"c:\videogames.json")) + using (JsonTextReader reader = new JsonTextReader(file)) + { + JObject o2 = (JObject) JToken.ReadFrom(reader); + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/SerializeWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/SerializeWithLinq.cs new file mode 100644 index 00000000..88cc4323 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/SerializeWithLinq.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class SerializeWithLinq + { + public class BlogPost + { + public string Title { get; set; } + public string AuthorName { get; set; } + public string AuthorTwitter { get; set; } + public string Body { get; set; } + public DateTime PostedDate { get; set; } + } + + public void Example() + { + IList blogPosts = new List + { + new BlogPost + { + Title = "Json.NET is awesome!", + AuthorName = "James Newton-King", + AuthorTwitter = "JamesNK", + PostedDate = new DateTime(2013, 1, 23, 19, 30, 0), + Body = @"

Title!

+

Content!

" + } + }; + + JArray blogPostsArray = new JArray( + blogPosts.Select(p => new JObject + { + {"Title", p.Title}, + { + "Author", new JObject + { + {"Name", p.AuthorName}, + {"Twitter", p.AuthorTwitter} + } + }, + {"Date", p.PostedDate}, + {"BodyHtml", HttpUtility.HtmlEncode(p.Body)}, + }) + ); + + Console.WriteLine(blogPostsArray.ToString()); + // [ + // { + // "Title": "Json.NET is awesome!", + // "Author": { + // "Name": "James Newton-King", + // "Twitter": "JamesNK" + // }, + // "Date": "2013-01-23T19:30:00", + // "BodyHtml": "<h3>Title!</h3>\r\n<p>Content!</p>" + // } + // ] + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectComplex.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectComplex.cs new file mode 100644 index 00000000..250e4cd3 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectComplex.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ToObjectComplex + { + public class Person + { + public string Name { get; set; } + } + + public void Example() + { + string json = @"{ + ""d"": [ + { + ""Name"": ""John Smith"" + }, + { + ""Name"": ""Mike Smith"" + } + ] + }"; + + JObject o = JObject.Parse(json); + + JArray a = (JArray)o["d"]; + + IList person = a.ToObject>(); + + Console.WriteLine(person[0].Name); + // John Smith + + Console.WriteLine(person[1].Name); + // Mike Smith + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectGeneric.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectGeneric.cs new file mode 100644 index 00000000..5390a829 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectGeneric.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ToObjectGeneric + { + public void Example() + { + JValue v1 = new JValue(true); + + bool b = v1.ToObject(); + + Console.WriteLine(b); + // true + + int i = v1.ToObject(); + + Console.WriteLine(i); + // 1 + + string s = v1.ToObject(); + + Console.WriteLine(s); + // "True" + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectType.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectType.cs new file mode 100644 index 00000000..8f7c0f4e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToObjectType.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ToObjectType + { + public void Example() + { + JValue v1 = new JValue(true); + + bool b = (bool)v1.ToObject(typeof(bool)); + + Console.WriteLine(b); + // true + + int i = (int)v1.ToObject(typeof(int)); + + Console.WriteLine(i); + // 1 + + string s = (string)v1.ToObject(typeof(string)); + + Console.WriteLine(s); + // "True" + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToString.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToString.cs new file mode 100644 index 00000000..932a1c63 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToString.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ToString + { + public void Example() + { + JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}"); + + Console.WriteLine(o.ToString()); + // { + // "string1": "value", + // "integer2": 99, + // "datetime3": "2000-05-23T00:00:00" + // } + + Console.WriteLine(o.ToString(Formatting.None)); + // {"string1":"value","integer2":99,"datetime3":"2000-05-23T00:00:00"} + + Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter())); + // {"string1":"value","integer2":99,"datetime3":new Date(959032800000)} + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToStringJsonConverter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToStringJsonConverter.cs new file mode 100644 index 00000000..2628c49e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ToStringJsonConverter.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ToStringJsonConverter + { + public void Example() + { + JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}"); + + Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter())); + // {"string1":"value","integer2":99,"datetime3":new Date(959032800000)} + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteToJsonFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteToJsonFile.cs new file mode 100644 index 00000000..57a4376f --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteToJsonFile.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class WriteToJsonFile + { + public void Example() + { + JObject videogameRatings = new JObject( + new JProperty("Halo", 9), + new JProperty("Starcraft", 9), + new JProperty("Call of Duty", 7.5)); + + File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString()); + + // write JSON directly to a file + using (StreamWriter file = File.CreateText(@"c:\videogames.json")) + using (JsonTextWriter writer = new JsonTextWriter(file)) + { + videogameRatings.WriteTo(writer); + } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/NullValueHandlingIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/NullValueHandlingIgnore.cs new file mode 100644 index 00000000..da6483c0 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/NullValueHandlingIgnore.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class NullValueHandlingIgnore + { + public class Person + { + public string Name { get; set; } + public int Age { get; set; } + public Person Partner { get; set; } + public decimal? Salary { get; set; } + } + + public void Example() + { + Person person = new Person + { + Name = "Nigal Newborn", + Age = 1 + }; + + string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented); + + Console.WriteLine(jsonIncludeNullValues); + // { + // "Name": "Nigal Newborn", + // "Age": 1, + // "Partner": null, + // "Salary": null + // } + + string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings + { + NullValueHandling = Json.NullValueHandling.Ignore + }); + + Console.WriteLine(jsonIgnoreNullValues); + // { + // "Name": "Nigal Newborn", + // "Age": 1 + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/PopulateObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/PopulateObject.cs new file mode 100644 index 00000000..e235746c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/PopulateObject.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class PopulateObject + { + public class Account + { + public string Email { get; set; } + public bool Active { get; set; } + public DateTime CreatedDate { get; set; } + public IList Roles { get; set; } + } + + public void Example() + { + Account account = new Account + { + Email = "james@example.com", + Active = true, + CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), + Roles = new List + { + "User", + "Admin" + } + }; + + string json = @"{ + ""Active"": false, + ""Roles"": [ + ""Expired"" + ] + }"; + + JsonConvert.PopulateObject(json, account); + + Console.WriteLine(account.Email); + // james@example.com + + Console.WriteLine(account.Active); + // false + + Console.WriteLine(string.Join(", ", account.Roles)); + // User, Admin, Expired + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/PropertyJsonIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/PropertyJsonIgnore.cs new file mode 100644 index 00000000..79f89fe5 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/PropertyJsonIgnore.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class PropertyJsonIgnore + { + public class Account + { + public string FullName { get; set; } + public string EmailAddress { get; set; } + [JsonIgnore] + public string PasswordHash { get; set; } + } + + public void Example() + { + Account account = new Account + { + FullName = "Joe User", + EmailAddress = "joe@example.com", + PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw==" + }; + + string json = JsonConvert.SerializeObject(account); + + Console.WriteLine(json); + // {"FullName":"Joe User","EmailAddress":"joe@example.com"} + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingIgnore.cs new file mode 100644 index 00000000..b9a32ca8 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingIgnore.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ReferenceLoopHandlingIgnore + { + public class Employee + { + public string Name { get; set; } + public Employee Manager { get; set; } + } + + public void Example() + { + Employee joe = new Employee { Name = "Joe User" }; + Employee mike = new Employee { Name = "Mike Manager" }; + joe.Manager = mike; + mike.Manager = mike; + + string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }); + + Console.WriteLine(json); + // { + // "Name": "Joe User", + // "Manager": { + // "Name": "Mike Manager" + // } + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingObject.cs new file mode 100644 index 00000000..27802116 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReferenceLoopHandlingObject.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ReferenceLoopHandlingObject + { + public class Directory + { + public string Name { get; set; } + public Directory Parent { get; set; } + public IList Files { get; set; } + } + + public class File + { + public string Name { get; set; } + public Directory Parent { get; set; } + } + + public void Example() + { + Directory root = new Directory { Name = "Root" }; + Directory documents = new Directory { Name = "My Documents", Parent = root }; + + File file = new File { Name = "ImportantLegalDocument.docx", Parent = documents }; + + documents.Files = new List { file }; + + try + { + JsonConvert.SerializeObject(documents, Formatting.Indented); + } + catch (JsonSerializationException) + { + // Self referencing loop detected for property 'Parent' with type + // 'Newtonsoft.Json.Tests.Documentation.Examples.ReferenceLoopHandlingObject+Directory'. Path 'Files[0]'. + } + + string preserveReferenacesAll = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings + { + PreserveReferencesHandling = PreserveReferencesHandling.All + }); + + Console.WriteLine(preserveReferenacesAll); + // { + // "$id": "1", + // "Name": "My Documents", + // "Parent": { + // "$id": "2", + // "Name": "Root", + // "Parent": null, + // "Files": null + // }, + // "Files": { + // "$id": "3", + // "$values": [ + // { + // "$id": "4", + // "Name": "ImportantLegalDocument.docx", + // "Parent": { + // "$ref": "1" + // } + // } + // ] + // } + // } + + string preserveReferenacesObjects = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings + { + PreserveReferencesHandling = PreserveReferencesHandling.Objects + }); + + Console.WriteLine(preserveReferenacesObjects); + // { + // "$id": "1", + // "Name": "My Documents", + // "Parent": { + // "$id": "2", + // "Name": "Root", + // "Parent": null, + // "Files": null + // }, + // "Files": [ + // { + // "$id": "3", + // "Name": "ImportantLegalDocument.docx", + // "Parent": { + // "$ref": "1" + // } + // } + // ] + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializationCallbackAttributes.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializationCallbackAttributes.cs new file mode 100644 index 00000000..deb98de4 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializationCallbackAttributes.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializationCallbackAttributes + { + public class SerializationEventTestObject + { + // 2222 + // This member is serialized and deserialized with no change. + public int Member1 { get; set; } + + // The value of this field is set and reset during and + // after serialization. + public string Member2 { get; set; } + + // This field is not serialized. The OnDeserializedAttribute + // is used to set the member value after serialization. + [JsonIgnore] + public string Member3 { get; set; } + + // This field is set to null, but populated after deserialization. + public string Member4 { get; set; } + + public SerializationEventTestObject() + { + Member1 = 11; + Member2 = "Hello World!"; + Member3 = "This is a nonserialized value"; + Member4 = null; + } + + [OnSerializing] + internal void OnSerializingMethod(StreamingContext context) + { + Member2 = "This value went into the data file during serialization."; + } + + [OnSerialized] + internal void OnSerializedMethod(StreamingContext context) + { + Member2 = "This value was reset after serialization."; + } + + [OnDeserializing] + internal void OnDeserializingMethod(StreamingContext context) + { + Member3 = "This value was set during deserialization"; + } + + [OnDeserialized] + internal void OnDeserializedMethod(StreamingContext context) + { + Member4 = "This value was set after deserialization."; + } + } + + public void Example() + { + SerializationEventTestObject obj = new SerializationEventTestObject(); + + Console.WriteLine(obj.Member1); + // 11 + Console.WriteLine(obj.Member2); + // Hello World! + Console.WriteLine(obj.Member3); + // This is a nonserialized value + Console.WriteLine(obj.Member4); + // null + + string json = JsonConvert.SerializeObject(obj, Formatting.Indented); + // { + // "Member1": 11, + // "Member2": "This value went into the data file during serialization.", + // "Member4": null + // } + + Console.WriteLine(obj.Member1); + // 11 + Console.WriteLine(obj.Member2); + // This value was reset after serialization. + Console.WriteLine(obj.Member3); + // This is a nonserialized value + Console.WriteLine(obj.Member4); + // null + + obj = JsonConvert.DeserializeObject(json); + + Console.WriteLine(obj.Member1); + // 11 + Console.WriteLine(obj.Member2); + // This value went into the data file during serialization. + Console.WriteLine(obj.Member3); + // This value was set during deserialization + Console.WriteLine(obj.Member4); + // This value was set after deserialization. + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeCollection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeCollection.cs new file mode 100644 index 00000000..2aefd84c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeCollection.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeCollection + { + public void Example() + { + List videogames = new List + { + "Starcraft", + "Halo", + "Legend of Zelda" + }; + + string json = JsonConvert.SerializeObject(videogames); + + Console.WriteLine(json); + // ["Starcraft","Halo","Legend of Zelda"] + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeContractResolver.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeContractResolver.cs new file mode 100644 index 00000000..b50fe16c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeContractResolver.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeContractResolver + { + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + + public string FullName + { + get { return FirstName + " " + LastName; } + } + } + + public void Example() + { + Person person = new Person + { + FirstName = "Sarah", + LastName = "Security" + }; + + string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings + { + ContractResolver = new CamelCasePropertyNamesContractResolver() + }); + + Console.WriteLine(json); + // { + // "firstName": "Sarah", + // "lastName": "Security", + // "fullName": "Sarah Security" + // } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateFormatHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateFormatHandling.cs new file mode 100644 index 00000000..1f527035 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateFormatHandling.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeDateFormatHandling + { + public void Example() + { + DateTime mayanEndOfTheWorld = new DateTime(2012, 12, 21); + + string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld); + + Console.WriteLine(jsonIsoDate); + // "2012-12-21T00:00:00" + + string jsonMsDate = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.MicrosoftDateFormat + }); + + Console.WriteLine(jsonMsDate); + // "\/Date(1356044400000+0100)\/" + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateTimeZoneHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateTimeZoneHandling.cs new file mode 100644 index 00000000..2dba555e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDateTimeZoneHandling.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeDateTimeZoneHandling + { + public class Flight + { + public string Destination { get; set; } + public DateTime DepartureDate { get; set; } + public DateTime DepartureDateUtc { get; set; } + public DateTime DepartureDateLocal { get; set; } + public TimeSpan Duration { get; set; } + } + + public void Example() + { + Flight flight = new Flight + { + Destination = "Dubai", + DepartureDate = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Unspecified), + DepartureDateUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Utc), + DepartureDateLocal = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local), + Duration = TimeSpan.FromHours(5.5) + }; + + string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind + }); + + Console.WriteLine(jsonWithRoundtripTimeZone); + // { + // "Destination": "Dubai", + // "DepartureDate": "2013-01-21T00:00:00", + // "DepartureDateUtc": "2013-01-21T00:00:00Z", + // "DepartureDateLocal": "2013-01-21T00:00:00+01:00", + // "Duration": "05:30:00" + // } + + string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Local + }); + + Console.WriteLine(jsonWithLocalTimeZone); + // { + // "Destination": "Dubai", + // "DepartureDate": "2013-01-21T00:00:00+01:00", + // "DepartureDateUtc": "2013-01-21T01:00:00+01:00", + // "DepartureDateLocal": "2013-01-21T00:00:00+01:00", + // "Duration": "05:30:00" + // } + + string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); + + Console.WriteLine(jsonWithUtcTimeZone); + // { + // "Destination": "Dubai", + // "DepartureDate": "2013-01-21T00:00:00Z", + // "DepartureDateUtc": "2013-01-21T00:00:00Z", + // "DepartureDateLocal": "2013-01-20T23:00:00Z", + // "Duration": "05:30:00" + // } + + string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Unspecified + }); + + Console.WriteLine(jsonWithUnspecifiedTimeZone); + // { + // "Destination": "Dubai", + // "DepartureDate": "2013-01-21T00:00:00", + // "DepartureDateUtc": "2013-01-21T00:00:00", + // "DepartureDateLocal": "2013-01-21T00:00:00", + // "Duration": "05:30:00" + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDictionary.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDictionary.cs new file mode 100644 index 00000000..5fdb4c1c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeDictionary.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeDictionary + { + public void Example() + { + Dictionary points = new Dictionary + { + { "James", 9001 }, + { "Jo", 3474 }, + { "Jess", 11926 } + }; + + string json = JsonConvert.SerializeObject(points, Formatting.Indented); + + Console.WriteLine(json); + // { + // "James": 9001, + // "Jo": 3474, + // "Jess": 11926 + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeObject.cs new file mode 100644 index 00000000..2966891c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeObject.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeObject + { + public class Account + { + public string Email { get; set; } + public bool Active { get; set; } + public DateTime CreatedDate { get; set; } + public IList Roles { get; set; } + } + + public void Example() + { + Account account = new Account + { + Email = "james@example.com", + Active = true, + CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), + Roles = new List + { + "User", + "Admin" + } + }; + + string json = JsonConvert.SerializeObject(account, Formatting.Indented); + // { + // "Email": "james@example.com", + // "Active": true, + // "CreatedDate": "2013-01-20T00:00:00Z", + // "Roles": [ + // "User", + // "Admin" + // ] + // } + + Console.WriteLine(json); + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeSerializationBinder.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeSerializationBinder.cs new file mode 100644 index 00000000..dfaa3c64 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeSerializationBinder.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeSerializationBinder + { + public class KnownTypesBinder : SerializationBinder + { + public IList KnownTypes { get; set; } + + public override Type BindToType(string assemblyName, string typeName) + { + return KnownTypes.SingleOrDefault(t => t.Name == typeName); + } + + public override void BindToName(Type serializedType, out string assemblyName, out string typeName) + { + assemblyName = null; + typeName = serializedType.Name; + } + } + + public class Car + { + public string Maker { get; set; } + public string Model { get; set; } + } + + public void Example() + { + KnownTypesBinder knownTypesBinder = new KnownTypesBinder + { + KnownTypes = new List {typeof (Car)} + }; + + Car car = new Car + { + Maker = "Ford", + Model = "Explorer" + }; + + string json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Objects, + Binder = knownTypesBinder + }); + + Console.WriteLine(json); + // { + // "$type": "Car", + // "Maker": "Ford", + // "Model": "Explorer" + // } + + object newValue = JsonConvert.DeserializeObject(json, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Objects, + Binder = knownTypesBinder + }); + + Console.WriteLine(newValue.GetType().Name); + // Car + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeToBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeToBson.cs new file mode 100644 index 00000000..a11bd944 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeToBson.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Bson; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeToBson + { + public class Event + { + public string Name { get; set; } + public DateTime StartDate { get; set; } + } + + public void Example() + { + Event e = new Event + { + Name = "Movie premier", + StartDate = new DateTime(2013, 1, 22, 20, 30, 0) + }; + + IList es = new List + { + e, e + }; + + MemoryStream ms = new MemoryStream(); + using (BsonWriter writer = new BsonWriter(ms)) + { + JsonSerializer serializer = new JsonSerializer(); + serializer.Serialize(writer, es); + } + + string data = Convert.ToBase64String(ms.ToArray()); + + Console.WriteLine(data); + // MAAAAAJOYW1lAA4AAABNb3ZpZSBwcmVtaWVyAAlTdGFydERhdGUAwOApYTwBAAAA + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeTypeNameHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeTypeNameHandling.cs new file mode 100644 index 00000000..629d9288 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeTypeNameHandling.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeTypeNameHandling + { + public abstract class Business + { + public string Name { get; set; } + } + + public class Hotel : Business + { + public int Stars { get; set; } + } + + public class Stockholder + { + public string FullName { get; set; } + public IList Businesses { get; set; } + } + + public void Example() + { + Stockholder stockholder = new Stockholder + { + FullName = "Steve Stockholder", + Businesses = new List + { + new Hotel + { + Name = "Hudson Hotel", + Stars = 4 + } + } + }; + + string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.All + }); + + Console.WriteLine(jsonTypeNameAll); + // { + // "$type": "Newtonsoft.Json.Tests.Documentation.Examples.SerializeTypeNameHandling+Stockholder, Newtonsoft.Json.Tests", + // "FullName": "Steve Stockholder", + // "Businesses": { + // "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Documentation.Examples.SerializeTypeNameHandling+Business, Newtonsoft.Json.Tests]], mscorlib", + // "$values": [ + // { + // "$type": "Newtonsoft.Json.Tests.Documentation.Examples.SerializeTypeNameHandling+Hotel, Newtonsoft.Json.Tests", + // "Stars": 4, + // "Name": "Hudson Hotel" + // } + // ] + // } + // } + + string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Auto + }); + + Console.WriteLine(jsonTypeNameAuto); + // { + // "FullName": "Steve Stockholder", + // "Businesses": [ + // { + // "$type": "Newtonsoft.Json.Tests.Documentation.Examples.SerializeTypeNameHandling+Hotel, Newtonsoft.Json.Tests", + // "Stars": 4, + // "Name": "Hudson Hotel" + // } + // ] + // } + + // for security TypeNameHandling is required when deserializing + Stockholder newStockholder = JsonConvert.DeserializeObject(jsonTypeNameAuto, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Auto + }); + + Console.WriteLine(newStockholder.Businesses[0].GetType().Name); + // Hotel + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeUnindentedJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeUnindentedJson.cs new file mode 100644 index 00000000..7cb2c33f --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeUnindentedJson.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeUnindentedJson + { + public class Account + { + public string Email { get; set; } + public bool Active { get; set; } + public DateTime CreatedDate { get; set; } + public IList Roles { get; set; } + } + + public void Example() + { + Account account = new Account + { + Email = "james@example.com", + Active = true, + CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), + Roles = new List + { + "User", + "Admin" + } + }; + + string json = JsonConvert.SerializeObject(account); + // {"Email":"james@example.com","Active":true,"CreatedDate":"2013-01-20T00:00:00Z","Roles":["User","Admin"]} + + Console.WriteLine(json); + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonConverters.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonConverters.cs new file mode 100644 index 00000000..a84d692c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonConverters.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Converters; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeWithJsonConverters + { + public void Example() + { + List stringComparisons = new List + { + StringComparison.CurrentCulture, + StringComparison.InvariantCulture + }; + + string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons); + + Console.WriteLine(jsonWithoutConverter); + // [0,2] + + string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons, new StringEnumConverter()); + + Console.WriteLine(jsonWithConverter); + // ["CurrentCulture","InvariantCulture"] + + List newStringComparsions = JsonConvert.DeserializeObject>(jsonWithConverter, new StringEnumConverter()); + + Console.WriteLine(string.Join(", ", newStringComparsions.Select(c => c.ToString()))); + // CurrentCulture, InvariantCulture + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonSerializerToFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonSerializerToFile.cs new file mode 100644 index 00000000..7786806c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeWithJsonSerializerToFile.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using File = System.IO.File; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeWithJsonSerializerToFile + { + public class Movie + { + public string Name { get; set; } + public int Year { get; set; } + } + + public void Example() + { + Movie movie = new Movie + { + Name = "Bad Boys", + Year = 1995 + }; + + // serialize JSON to a string and then write string to a file + File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie)); + + // serialize JSON directly to a file + using (StreamWriter file = File.CreateText(@"c:\movie.json")) + { + JsonSerializer serializer = new JsonSerializer(); + serializer.Serialize(file, movie); + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/TraceWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/TraceWriter.cs new file mode 100644 index 00000000..566cc041 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/TraceWriter.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class TraceWriter + { + public class Account + { + public string FullName { get; set; } + public bool Deleted { get; set; } + } + + public void Example() + { + string json = @"{ + ""FullName"": ""Dan Deleted"", + ""Deleted"": true, + ""DeletedDate"": ""2013-01-20T00:00:00"" + }"; + + MemoryTraceWriter traceWriter = new MemoryTraceWriter(); + + Account account = JsonConvert.DeserializeObject(json, new JsonSerializerSettings + { + TraceWriter = traceWriter + }); + + Console.WriteLine(traceWriter.ToString()); + // 2013-01-21T01:36:24.422 Info Started deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'FullName', line 2, position 20. + // 2013-01-21T01:36:24.442 Verbose Could not find member 'DeletedDate' on Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'DeletedDate', line 4, position 23. + // 2013-01-21T01:36:24.447 Info Finished deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path '', line 5, position 8. + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs index 4ae7b133..4626449d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs @@ -56,6 +56,21 @@ namespace Newtonsoft.Json.Tests.Documentation { return null; } + + public static StreamWriter CreateText(string path) + { + return null; + } + + public static void WriteAllText(string path, string contents) + { + Console.WriteLine(contents); + } + + public static string ReadAllText(string path) + { + return null; + } } public class LinqToJsonTests diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs index e06cc4cd..6874a439 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs @@ -981,6 +981,11 @@ namespace Newtonsoft.Json.Tests.Linq t = o.SelectToken("Test3.Test1[1].Test1"); Assert.AreEqual("Test3.Test1[1].Test1", t.Path); + + JArray a = new JArray(1); + Assert.AreEqual("", a.Path); + + Assert.AreEqual("[0]", a[0].Path); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index 0bc8b319..c0fa665b 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -54,6 +54,7 @@ prompt 4 AllRules.ruleset + true pdbonly @@ -118,6 +119,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index 91f4cbe2..5b3624f8 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -76,5 +76,5 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.0.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.5.11.15631")] +[assembly: AssemblyFileVersion("4.5.11.15716")] #endif diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs index dc79c1c1..8af22869 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs @@ -565,5 +565,85 @@ namespace Newtonsoft.Json.Tests.Schema Assert.AreEqual(JsonSchemaType.Object, schema.Properties["slash"].Type); Assert.AreEqual(JsonSchemaType.Array, schema.Properties["percent"].Type); } + + [Test] + public void References_Array() + { + string json = @"{ + ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}], + ""properties"": { + ""array"": {""$ref"": ""#/array/0""}, + ""arrayprop"": {""$ref"": ""#/array/1/prop""} + } + }"; + + JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); + JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); + + Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["array"].Type); + Assert.AreEqual(JsonSchemaType.Object, schema.Properties["arrayprop"].Type); + } + + [Test] + public void References_IndexTooBig() + { + // JsonException : Could not resolve schema reference '#/array/10'. + + string json = @"{ + ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}], + ""properties"": { + ""array"": {""$ref"": ""#/array/0""}, + ""arrayprop"": {""$ref"": ""#/array/10""} + } + }"; + + ExceptionAssert.Throws( + "Could not resolve schema reference '#/array/10'.", + () => + { + JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); + builder.Read(new JsonTextReader(new StringReader(json))); + }); + } + + [Test] + public void References_IndexNegative() + { + string json = @"{ + ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}], + ""properties"": { + ""array"": {""$ref"": ""#/array/0""}, + ""arrayprop"": {""$ref"": ""#/array/-1""} + } + }"; + + ExceptionAssert.Throws( + "Could not resolve schema reference '#/array/-1'.", + () => + { + JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); + builder.Read(new JsonTextReader(new StringReader(json))); + }); + } + + [Test] + public void References_IndexNotInteger() + { + string json = @"{ + ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}], + ""properties"": { + ""array"": {""$ref"": ""#/array/0""}, + ""arrayprop"": {""$ref"": ""#/array/one""} + } + }"; + + ExceptionAssert.Throws( + "Could not resolve schema reference '#/array/one'.", + () => + { + JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); + builder.Read(new JsonTextReader(new StringReader(json))); + }); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs index debd31f7..515e450a 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs @@ -54,8 +54,6 @@ namespace Newtonsoft.Json.Tests.Schema string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; string baseTestPath = Path.Combine(baseDirectory, "Schema", "Specs"); - Console.WriteLine("Loading JSON Schema tests from " + baseTestPath); - string[] testFiles = Directory.GetFiles(baseTestPath, "*.json", SearchOption.AllDirectories); // read through each of the *.json test files and extract the test details diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs index 9e8c7483..8827a02d 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs @@ -23,6 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion +using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json.Linq; @@ -119,6 +120,89 @@ namespace Newtonsoft.Json.Tests.Schema }", writtenJson); } + [Test] + public void Extends_Multiple() + { + string json = @"{ + ""type"":""object"", + ""extends"":{""type"":""string""}, + ""additionalProperties"":{""type"":""string""} +}"; + + JsonSchema s = JsonSchema.Parse(json); + + StringWriter writer = new StringWriter(); + JsonTextWriter jsonWriter = new JsonTextWriter(writer); + jsonWriter.Formatting = Formatting.Indented; + + string newJson = s.ToString(); + + Assert.AreEqual(@"{ + ""type"": ""object"", + ""additionalProperties"": { + ""type"": ""string"" + }, + ""extends"": { + ""type"": ""string"" + } +}", newJson); + + + json = @"{ + ""type"":""object"", + ""extends"":[{""type"":""string""}], + ""additionalProperties"":{""type"":""string""} +}"; + + s = JsonSchema.Parse(json); + + writer = new StringWriter(); + jsonWriter = new JsonTextWriter(writer); + jsonWriter.Formatting = Formatting.Indented; + + newJson = s.ToString(); + + Assert.AreEqual(@"{ + ""type"": ""object"", + ""additionalProperties"": { + ""type"": ""string"" + }, + ""extends"": { + ""type"": ""string"" + } +}", newJson); + + + json = @"{ + ""type"":""object"", + ""extends"":[{""type"":""string""},{""type"":""object""}], + ""additionalProperties"":{""type"":""string""} +}"; + + s = JsonSchema.Parse(json); + + writer = new StringWriter(); + jsonWriter = new JsonTextWriter(writer); + jsonWriter.Formatting = Formatting.Indented; + + newJson = s.ToString(); + + Assert.AreEqual(@"{ + ""type"": ""object"", + ""additionalProperties"": { + ""type"": ""string"" + }, + ""extends"": [ + { + ""type"": ""string"" + }, + { + ""type"": ""object"" + } + ] +}", newJson); + } + [Test] public void WriteTo_AdditionalProperties() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 7333aa27..9217e875 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -7216,6 +7216,108 @@ Parameter name: value", } }", json); } + + [Test] + public void DeserializeDecimal() + { + JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456")); + var settings = new JsonSerializerSettings(); + var serialiser = JsonSerializer.Create(settings); + decimal? d = serialiser.Deserialize(reader); + + Assert.AreEqual(1234567890.123456m, d); + } + + [Test] + public void DontSerializeStaticFields() + { + string json = + JsonConvert.SerializeObject(new AnswerFilterModel(), Formatting.Indented, new JsonSerializerSettings + { + ContractResolver = new DefaultContractResolver + { + IgnoreSerializableAttribute = false + } + }); + + Assert.AreEqual(@"{ + ""k__BackingField"": false, + ""k__BackingField"": false, + ""k__BackingField"": false, + ""k__BackingField"": false, + ""k__BackingField"": false, + ""k__BackingField"": false +}", json); + } + } + + public enum Antworten + { + First, + Second + } + + public class SelectListItem + { + public string Text { get; set; } + public string Value { get; set; } + public bool Selected { get; set; } + } + + [Serializable] + public class AnswerFilterModel + { + [NonSerialized] + private readonly IList answerValues; + + /// + /// Initializes a new instance of the class. + /// + public AnswerFilterModel() + { + this.answerValues = (from answer in Enum.GetNames(typeof(Antworten)) + select new SelectListItem { Text = answer, Value = answer, Selected = false }) + .ToList(); + } + + /// + /// Gets or sets a value indicating whether active. + /// + public bool Active { get; set; } + + /// + /// Gets or sets a value indicating whether ja. + /// nach bisherigen Antworten. + /// + public bool Ja { get; set; } + + /// + /// Gets or sets a value indicating whether handlungsbedarf. + /// + public bool Handlungsbedarf { get; set; } + + /// + /// Gets or sets a value indicating whether beratungsbedarf. + /// + public bool Beratungsbedarf { get; set; } + + /// + /// Gets or sets a value indicating whether unzutreffend. + /// + public bool Unzutreffend { get; set; } + + /// + /// Gets or sets a value indicating whether unbeantwortet. + /// + public bool Unbeantwortet { get; set; } + + /// + /// Gets the answer values. + /// + public IEnumerable AnswerValues + { + get { return this.answerValues; } + } } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) diff --git a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs index 7cb651ba..55fc3c75 100644 --- a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs +++ b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs @@ -96,11 +96,13 @@ namespace Newtonsoft.Json.Tests { public static void IsInstanceOfType(Type t, object instance) { -#if !NETFX_CORE +#if (WINDOWS_PHONE || SILVERLIGHT) Assert.IsInstanceOfType(t, instance); -#else +#elif NETFX_CORE if (!instance.GetType().IsAssignableFrom(t)) - throw new Exception("Blah"); + throw new Exception("Not instance of type"); +#else + Assert.IsInstanceOf(t, instance); #endif } diff --git a/Src/Newtonsoft.Json/JsonSerializationException.cs b/Src/Newtonsoft.Json/JsonSerializationException.cs index 55962a7e..3d132ddc 100644 --- a/Src/Newtonsoft.Json/JsonSerializationException.cs +++ b/Src/Newtonsoft.Json/JsonSerializationException.cs @@ -90,7 +90,7 @@ namespace Newtonsoft.Json return Create(reader as IJsonLineInfo, reader.Path, message, ex); } - internal static new JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 14e406b5..95403653 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -167,6 +167,51 @@ namespace Newtonsoft.Json.Linq internal set { _previous = value; } } + /// + /// Gets the path of the JSON token. + /// + public string Path + { + get + { + if (Parent == null) + return string.Empty; + + IList ancestors = Ancestors().Reverse().ToList(); + ancestors.Add(this); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < ancestors.Count; i++) + { + JToken current = ancestors[i]; + JToken next = (i + 1 < ancestors.Count) ? ancestors[i + 1] : null; + + if (next != null) + { + switch (current.Type) + { + case JTokenType.Property: + JProperty property = (JProperty)current; + + if (sb.Length > 0) + sb.Append("."); + + sb.Append(property.Name); + break; + case JTokenType.Array: + case JTokenType.Constructor: + int index = ((IList)current).IndexOf(next); + + sb.Append("[" + index + "]"); + break; + } + } + } + + return sb.ToString(); + } + } + internal JToken() { } @@ -1700,44 +1745,5 @@ namespace Newtonsoft.Json.Linq { return CloneToken(); } - - public string Path - { - get - { - IList ancestors = Ancestors().Reverse().ToList(); - ancestors.Add(this); - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ancestors.Count; i++) - { - JToken current = ancestors[i]; - JToken next = (i + 1 < ancestors.Count) ? ancestors[i + 1] : null; - - if (next != null) - { - switch (current.Type) - { - case JTokenType.Property: - JProperty property = (JProperty) current; - - if (sb.Length > 0) - sb.Append("."); - - sb.Append(property.Name); - break; - case JTokenType.Array: - case JTokenType.Constructor: - int index = ((IList)current).IndexOf(next); - - sb.Append("[" + index + "]"); - break; - } - } - } - - return sb.ToString(); - } - } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index 81ac0554..9dafe9d6 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -90,7 +90,7 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.0.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.5.11.15631")] +[assembly: AssemblyFileVersion("4.5.11.15716")] #endif [assembly: CLSCompliant(true)] diff --git a/Src/Newtonsoft.Json/Schema/JsonSchema.cs b/Src/Newtonsoft.Json/Schema/JsonSchema.cs index 2811d61a..d4a3b36d 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchema.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchema.cs @@ -201,7 +201,7 @@ namespace Newtonsoft.Json.Schema /// The format. public string Format { get; set; } - public string Location { get; set; } + internal string Location { get; set; } private readonly string _internalId = Guid.NewGuid().ToString("N"); diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index 0c7694a4..08b4fd4e 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -120,7 +120,7 @@ namespace Newtonsoft.Json.Schema else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor) { int index; - if (int.TryParse(part, out index)) + if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count()) currentToken = currentToken[index]; else currentToken = null; diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 7b618097..68b0371c 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -319,7 +319,8 @@ namespace Newtonsoft.Json.Serialization // serialize all fields foreach (MemberInfo member in allMembers) { - if (member.MemberType() == MemberTypes.Field) + FieldInfo field = member as FieldInfo; + if (field != null && !field.IsStatic) serializableMembers.Add(member); } }