diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertJsonToXml.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertJsonToXml.cs new file mode 100644 index 00000000..9c3830c0 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertJsonToXml.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Xml.Linq; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ConvertJsonToXml + { + public void Example() + { + string json = @"{ + ""@Id"": 1, + ""Email"": ""james@example.com"", + ""Active"": true, + ""CreatedDate"": ""2013-01-20T00:00:00Z"", + ""Roles"": [ + ""User"", + ""Admin"" + ], + ""Team"": { + ""@Id"": 2, + ""Name"": ""Software Developers"", + ""Description"": ""Creators of fine software products and services."" + } + }"; + + XNode node = JsonConvert.DeserializeXNode(json, "Root"); + + Console.WriteLine(node.ToString()); + // + // james@example.com + // true + // 2013-01-20T00:00:00Z + // User + // Admin + // + // Software Developers + // Creators of fine software products and services. + // + // + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertXmlToJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertXmlToJson.cs new file mode 100644 index 00000000..b25f9648 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertXmlToJson.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Xml; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ConvertXmlToJson + { + public void Example() + { + string xml = @" + + + Alan + http://www.google.com + + + Louis + http://www.yahoo.com + + "; + + XmlDocument doc = new XmlDocument(); + doc.LoadXml(xml); + + string json = JsonConvert.SerializeXmlNode(doc); + + Console.WriteLine(json); + // { + // "?xml": { + // "@version": "1.0", + // "@standalone": "no" + // }, + // "root": { + // "person": [ + // { + // "@id": "1", + // "name": "Alan", + // "url": "http://www.google.com" + // }, + // { + // "@id": "2", + // "name": "Louis", + // "url": "http://www.yahoo.com" + // } + // ] + // } + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertXmlToJsonForceArray.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertXmlToJsonForceArray.cs new file mode 100644 index 00000000..94c72ecf --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ConvertXmlToJsonForceArray.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Xml; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ConvertXmlToJsonForceArray + { + public void Example() + { + string xml = @" + Alan + http://www.google.com + Admin1 + "; + + XmlDocument doc = new XmlDocument(); + doc.LoadXml(xml); + + string json = JsonConvert.SerializeXmlNode(doc); + + Console.WriteLine(json); + // { + // "person": { + // "@id": "1", + // "name": "Alan", + // "url": "http://www.google.com", + // "role": "Admin1" + // } + // } + + xml = @" + Alan + http://www.google.com + Admin + "; + + doc = new XmlDocument(); + doc.LoadXml(xml); + + json = JsonConvert.SerializeXmlNode(doc); + + Console.WriteLine(json); + // { + // "person": { + // "@id": "1", + // "name": "Alan", + // "url": "http://www.google.com", + // "role": [ + // "Admin" + // ] + // } + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomJsonConverter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomJsonConverter.cs new file mode 100644 index 00000000..4671487a --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomJsonConverter.cs @@ -0,0 +1,96 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class CustomJsonConverter + { + public class KeysJsonConverter : JsonConverter + { + private Type[] _types; + + public KeysJsonConverter(params Type[] types) + { + _types = types; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + JToken t = JToken.FromObject(value); + + if (t.Type != JTokenType.Object) + { + t.WriteTo(writer); + } + else + { + JObject o = (JObject)t; + IList propertyNames = o.Properties().Select(p => p.Name).ToList(); + + o.AddFirst(new JProperty("Keys", new JArray(propertyNames))); + + o.WriteTo(writer); + } + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + throw new NotImplementedException("This is not necessary because CanRead is false so the type will be deserialized as normal."); + } + + public override bool CanRead + { + get { return false; } + } + + public override bool CanConvert(Type objectType) + { + return _types.Any(t => t == objectType); + } + } + + public class Employee + { + public string FirstName { get; set; } + public string LastName { get; set; } + public IList Roles { get; set; } + } + + public void Example() + { + Employee employee = new Employee + { + FirstName = "James", + LastName = "Newton-King", + Roles = new List + { + "Admin" + } + }; + + string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new KeysJsonConverter(typeof(Employee))); + + Console.WriteLine(json); + // { + // "Keys": [ + // "FirstName", + // "LastName", + // "Roles" + // ], + // "FirstName": "James", + // "LastName": "Newton-King", + // "Roles": [ + // "Admin" + // ] + // } + + Employee newEmployee = JsonConvert.DeserializeObject(json, new KeysJsonConverter(typeof(Employee))); + + Console.WriteLine(newEmployee.FirstName); + // James + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomTraceWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomTraceWriter.cs new file mode 100644 index 00000000..5c4f746c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/CustomTraceWriter.cs @@ -0,0 +1,77 @@ +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class CustomTraceWriter + { + public class NLogTraceWriter : ITraceWriter + { + private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter"); + + public TraceLevel LevelFilter + { + // trace all messages. nlog can handle filtering + get { return TraceLevel.Verbose; } + } + + public void Trace(TraceLevel level, string message, Exception ex) + { + LogEventInfo logEvent = new LogEventInfo + { + Message = message, + Level = GetLogLevel(level), + Exception = ex + }; + + // log Json.NET message to NLog + Logger.Log(logEvent); + } + + private LogLevel GetLogLevel(TraceLevel level) + { + switch (level) + { + case TraceLevel.Error: + return LogLevel.Error; + case TraceLevel.Warning: + return LogLevel.Warn; + case TraceLevel.Info: + return LogLevel.Info; + case TraceLevel.Off: + return LogLevel.Off; + default: + return LogLevel.Trace; + } + } + } + + public void Example() + { + IList countries = new List + { + "New Zealand", + "Australia", + "Denmark", + "China" + }; + + string json = JsonConvert.SerializeObject(countries, Formatting.Indented, new JsonSerializerSettings + { + TraceWriter = new NLogTraceWriter() + }); + + Console.WriteLine(json); + // [ + // "New Zealand", + // "Australia", + // "Denmark", + // "China" + // ] + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerFromFile.cs similarity index 93% rename from Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs rename to Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerFromFile.cs index 4a65b7d8..7ab67199 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerToFile.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/DeserializeWithJsonSerializerFromFile.cs @@ -7,7 +7,7 @@ using File = System.IO.File; namespace Newtonsoft.Json.Tests.Documentation.Examples { - public class DeserializeWithJsonSerializerToFile + public class DeserializeWithJsonSerializerFromFile { public class Movie { diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingAttribute.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingAttribute.cs new file mode 100644 index 00000000..fadfa9d3 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ErrorHandlingAttribute.cs @@ -0,0 +1,58 @@ +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ErrorHandlingAttribute + { + public class Employee + { + private List _roles; + + public string Name { get; set; } + public int Age { get; set; } + public List Roles + { + get + { + if (_roles == null) + throw new Exception("Roles not loaded!"); + + return _roles; + } + set { _roles = value; } + } + public string Title { get; set; } + + [OnError] + internal void OnError(StreamingContext context, ErrorContext errorContext) + { + errorContext.Handled = true; + } + } + + public void Example() + { + Employee person = new Employee + { + Name = "George Michael Bluth", + Age = 16, + Roles = null, + Title = "Mister Manager" + }; + + string json = JsonConvert.SerializeObject(person, Formatting.Indented); + + Console.WriteLine(json); + // { + // "Name": "George Michael Bluth", + // "Age": 16, + // "Title": "Mister Manager" + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJson.cs new file mode 100644 index 00000000..9f416104 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJson.cs @@ -0,0 +1,67 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class QueryJson + { + public void Example() + { + string json = @"{ + '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' + ] + } + ] + } + }"; + + JObject rss = JObject.Parse(json); + + string rssTitle = (string)rss["channel"]["title"]; + + Console.WriteLine(rssTitle); + // James Newton-King + + string itemTitle = (string)rss["channel"]["item"][0]["title"]; + + Console.WriteLine(itemTitle); + // Json.NET 1.3 + New license + Now on CodePlex + + JArray categories = (JArray)rss["channel"]["item"][0]["category"]; + + Console.WriteLine(categories); + // [ + // "Json.NET", + // "CodePlex" + // ] + + IList categoriesText = categories.Select(c => (string)c).ToList(); + + Console.WriteLine(string.Join(", ", categoriesText)); + // Json.NET, CodePlex + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonLinq.cs new file mode 100644 index 00000000..20e34e85 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonLinq.cs @@ -0,0 +1,71 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class QueryJsonLinq + { + public void Example() + { + string json = @"{ + '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' + ] + } + ] + } + }"; + + JObject rss = JObject.Parse(json); + + var postTitles = + from p in rss["channel"]["item"] + select (string)p["title"]; + + foreach (var item in postTitles) + { + Console.WriteLine(item); + } + + //LINQ to JSON beta + //Json.NET 1.3 + New license + Now on CodePlex + + var categories = + from c in rss["channel"]["item"].Children()["category"].Values() + group c by c into g + orderby g.Count() descending + select new { Category = g.Key, Count = g.Count() }; + + foreach (var c in categories) + { + Console.WriteLine(c.Category + " - Count: " + c.Count); + } + + //Json.NET - Count: 2 + //LINQ - Count: 1 + //CodePlex - Count: 1 + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonSelectToken.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonSelectToken.cs new file mode 100644 index 00000000..d911f6ef --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonSelectToken.cs @@ -0,0 +1,60 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class QueryJsonSelectToken + { + public void Example() + { + JObject o = JObject.Parse(@"{ + 'Stores': [ + 'Lambton Quay', + 'Willis Street' + ], + 'Manufacturers': [ + { + 'Name': 'Acme Co', + 'Products': [ + { + 'Name': 'Anvil', + 'Price': 50 + } + ] + }, + { + 'Name': 'Contoso', + 'Products': [ + { + 'Name': 'Elbow Grease', + 'Price': 99.95 + }, + { + 'Name': 'Headlight Fluid', + 'Price': 4 + } + ] + } + ] + }"); + + string name = (string)o.SelectToken("Manufacturers[0].Name"); + + Console.WriteLine(name); + // Acme Co + + decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price"); + + Console.WriteLine(productPrice); + // 50 + + string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name"); + + Console.WriteLine(productName); + // Elbow Grease + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonSelectTokenWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonSelectTokenWithLinq.cs new file mode 100644 index 00000000..784e68d1 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/QueryJsonSelectTokenWithLinq.cs @@ -0,0 +1,60 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class QueryJsonSelectTokenWithLinq + { + public void Example() + { + JObject o = JObject.Parse(@"{ + 'Stores': [ + 'Lambton Quay', + 'Willis Street' + ], + 'Manufacturers': [ + { + 'Name': 'Acme Co', + 'Products': [ + { + 'Name': 'Anvil', + 'Price': 50 + } + ] + }, + { + 'Name': 'Contoso', + 'Products': [ + { + 'Name': 'Elbow Grease', + 'Price': 99.95 + }, + { + 'Name': 'Headlight Fluid', + 'Price': 4 + } + ] + } + ] + }"); + + IList storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList(); + + Console.WriteLine(string.Join(", ", storeNames)); + // Lambton Quay, Willis Street + + IList firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).Where(n => n != null).ToList(); + + Console.WriteLine(string.Join(", ", firstProductNames)); + // Headlight Fluid + + decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price")); + + Console.WriteLine(totalPrice); + // 149.95 + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJTokenFromBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJTokenFromBson.cs new file mode 100644 index 00000000..c3bc42d6 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/ReadJTokenFromBson.cs @@ -0,0 +1,30 @@ +using Newtonsoft.Json.Bson; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class ReadJTokenFromBson + { + public void Example() + { + byte[] data = Convert.FromBase64String("KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA="); + MemoryStream ms = new MemoryStream(data); + + JObject o; + using (BsonReader reader = new BsonReader(ms)) + { + o = (JObject)JToken.ReadFrom(reader); + } + + string value = (string)o["name1"]; + + Console.WriteLine(value); + // value1 + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteJTokenToBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteJTokenToBson.cs new file mode 100644 index 00000000..e10ee3e7 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Linq/WriteJTokenToBson.cs @@ -0,0 +1,33 @@ +using Newtonsoft.Json.Bson; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq +{ + public class WriteJTokenToBson + { + public void Example() + { + JObject o = new JObject + { + {"name1","value1"}, + {"name2","value2"} + }; + + MemoryStream ms = new MemoryStream(); + using (BsonWriter writer = new BsonWriter(ms)) + { + o.WriteTo(writer); + } + + string data = Convert.ToBase64String(ms.ToArray()); + + Console.WriteLine(data); + // KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA= + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReadJsonWithJsonTextReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReadJsonWithJsonTextReader.cs new file mode 100644 index 00000000..e9cdc5a2 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/ReadJsonWithJsonTextReader.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class ReadJsonWithJsonTextReader + { + public void Example() + { + string json = @"{ + 'CPU': 'Intel', + 'PSU': '500W', + 'Drives': [ + 'DVD read/writer' + /*(broken)*/, + '500 gigabyte hard drive', + '200 gigabype hard drive' + ] + }"; + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + while (reader.Read()) + { + if (reader.Value != null) + Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); + else + Console.WriteLine("Token: {0}", reader.TokenType); + } + + // Token: StartObject + // Token: PropertyName, Value: CPU + // Token: String, Value: Intel + // Token: PropertyName, Value: PSU + // Token: String, Value: 500W + // Token: PropertyName, Value: Drives + // Token: StartArray + // Token: String, Value: DVD read/writer + // Token: Comment, Value: (broken) + // Token: String, Value: 500 gigabyte hard drive + // Token: String, Value: 200 gigabype hard drive + // Token: EndArray + // Token: EndObject + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/CreateJsonSchemaManually.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/CreateJsonSchemaManually.cs new file mode 100644 index 00000000..ae6a51c5 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/CreateJsonSchemaManually.cs @@ -0,0 +1,57 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class CreateJsonSchemaManually + { + public void Example() + { + JsonSchema schema = new JsonSchema(); + schema.Type = JsonSchemaType.Object; + schema.Properties = new Dictionary + { + {"name", new JsonSchema {Type = JsonSchemaType.String}}, + { + "hobbies", new JsonSchema + { + Type = JsonSchemaType.Array, + Items = new List { new JsonSchema {Type = JsonSchemaType.String} } + } + }, + }; + + string schemaJson = schema.ToString(); + + Console.WriteLine(schemaJson); + // { + // "type": "object", + // "properties": { + // "name": { + // "type": "string" + // }, + // "hobbies": { + // "type": "array", + // "items": { + // "type": "string" + // } + // } + // } + // } + + JObject person = JObject.Parse(@"{ + 'name': 'James', + 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + }"); + + bool valid = person.IsValid(schema); + + Console.WriteLine(valid); + // true + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenIsValid.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenIsValid.cs new file mode 100644 index 00000000..9e073d60 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenIsValid.cs @@ -0,0 +1,39 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class JTokenIsValid + { + public void Example() + { + string schemaJson = @"{ + 'description': 'A person', + 'type': 'object', + 'properties': { + 'name': {'type':'string'}, + 'hobbies': { + 'type': 'array', + 'items': {'type':'string'} + } + } + }"; + + JsonSchema schema = JsonSchema.Parse(schemaJson); + + JObject person = JObject.Parse(@"{ + 'name': 'James', + 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + }"); + + bool valid = person.IsValid(schema); + + Console.WriteLine(valid); + // true + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenIsValidWithMessages.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenIsValidWithMessages.cs new file mode 100644 index 00000000..172d3a81 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenIsValidWithMessages.cs @@ -0,0 +1,47 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class JTokenIsValidWithMessages + { + public void Example() + { + string schemaJson = @"{ + 'description': 'A person', + 'type': 'object', + 'properties': { + 'name': {'type':'string'}, + 'hobbies': { + 'type': 'array', + 'items': {'type':'string'} + } + } + }"; + + JsonSchema schema = JsonSchema.Parse(schemaJson); + + JObject person = JObject.Parse(@"{ + 'name': null, + 'hobbies': ['Invalid content', 0.123456789] + }"); + + IList messages; + bool valid = person.IsValid(schema, out messages); + + Console.WriteLine(valid); + // false + + foreach (string message in messages) + { + Console.WriteLine(message); + } + // Invalid type. Expected String but got Null. Line 2, position 21. + // Invalid type. Expected String but got Float. Line 3, position 51. + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenValidateWithEvent.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenValidateWithEvent.cs new file mode 100644 index 00000000..c98ba7ab --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JTokenValidateWithEvent.cs @@ -0,0 +1,46 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class JTokenValidateWithEvent + { + public void Example() + { + string schemaJson = @"{ + 'description': 'A person', + 'type': 'object', + 'properties': { + 'name': {'type':'string'}, + 'hobbies': { + 'type': 'array', + 'items': {'type':'string'} + } + } + }"; + + JsonSchema schema = JsonSchema.Parse(schemaJson); + + JObject person = JObject.Parse(@"{ + 'name': null, + 'hobbies': ['Invalid content', 0.123456789] + }"); + + IList messages = new List(); + ValidationEventHandler validationEventHandler = (sender, args) => { messages.Add(args.Message); }; + + person.Validate(schema, validationEventHandler); + + foreach (string message in messages) + { + Console.WriteLine(message); + } + // Invalid type. Expected String but got Null. Line 2, position 21. + // Invalid type. Expected String but got Float. Line 3, position 51. + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonSchemaLoad.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonSchemaLoad.cs new file mode 100644 index 00000000..725ba4c0 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonSchemaLoad.cs @@ -0,0 +1,32 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class JsonSchemaLoad + { + public void Example() + { + string schemaJson = @"{'type': 'object'}"; + + JsonSchema schema; + using (TextReader file = File.OpenText(@"c:\schema.json")) + using (JsonTextReader reader = new JsonTextReader(file)) + { + schema = JsonSchema.Read(reader); + } + + JObject o = JObject.Parse(@"{}"); + + bool valid = o.IsValid(schema); + + Console.WriteLine(valid); + // true + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonSchemaParse.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonSchemaParse.cs new file mode 100644 index 00000000..28137f7d --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonSchemaParse.cs @@ -0,0 +1,39 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class JsonSchemaParse + { + public void Example() + { + string schemaJson = @"{ + 'description': 'A person', + 'type': 'object', + 'properties': { + 'name': {'type':'string'}, + 'hobbies': { + 'type': 'array', + 'items': {'type':'string'} + } + } + }"; + + JsonSchema schema = JsonSchema.Parse(schemaJson); + + Console.WriteLine(schema.Type); + // Object + + foreach (var property in schema.Properties) + { + Console.WriteLine(property.Key + " - " + property.Value.Type); + } + // name - String + // hobbies - Array + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonValidatingReaderAndSerializer.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonValidatingReaderAndSerializer.cs new file mode 100644 index 00000000..94eabfc4 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/JsonValidatingReaderAndSerializer.cs @@ -0,0 +1,57 @@ +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class JsonValidatingReaderAndSerializer + { + public class Person + { + public string Name { get; set; } + public IList Hobbies { get; set; } + } + + public void Example() + { + string schemaJson = @"{ + 'description': 'A person', + 'type': 'object', + 'properties': { + 'name': {'type':'string'}, + 'hobbies': { + 'type': 'array', + 'items': {'type':'string'} + } + } + }"; + + string json = @"{ + 'name': 'James', + 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + }"; + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + + JsonValidatingReader validatingReader = new JsonValidatingReader(reader); + validatingReader.Schema = JsonSchema.Parse(schemaJson); + + IList messages = new List(); + validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message); + + JsonSerializer serializer = new JsonSerializer(); + Person p = serializer.Deserialize(validatingReader); + + Console.WriteLine(p.Name); + // James + + bool isValid = (messages.Count == 0); + + Console.WriteLine(isValid); + // true + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/LoadJsonSchemaFromFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/LoadJsonSchemaFromFile.cs new file mode 100644 index 00000000..9f929fa2 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/LoadJsonSchemaFromFile.cs @@ -0,0 +1,25 @@ +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class LoadJsonSchemaFromFile + { + public void Example() + { + // read file into a string and parse JsonSchema from the string + JsonSchema schema1 = JsonSchema.Parse(File.ReadAllText(@"c:\schema.json")); + + // read JsonSchema directly from a file + using (StreamReader file = File.OpenText(@"c:\schema.json")) + using (JsonTextReader reader = new JsonTextReader(file)) + { + JsonSchema schema2 = JsonSchema.Read(reader); + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/RefJsonSchemaResolver.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/RefJsonSchemaResolver.cs new file mode 100644 index 00000000..af61ce32 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/RefJsonSchemaResolver.cs @@ -0,0 +1,55 @@ +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class RefJsonSchemaResolver + { + public void Example() + { + string schemaJson; + JsonSchemaResolver resolver = new JsonSchemaResolver(); + + schemaJson = @"{ + ""id"": ""person"", + ""type"": ""object"", + ""properties"": { + ""name"": {""type"":""string""}, + ""age"": {""type"":""integer""} + } + }"; + + JsonSchema personSchema = JsonSchema.Parse(schemaJson, resolver); + + schemaJson = @"{ + ""id"": ""employee"", + ""type"": ""object"", + ""extends"": {""$ref"":""person""}, + ""properties"": { + ""salary"": {""type"":""number""}, + ""jobTitle"": {""type"":""string""} + } + }"; + + JsonSchema employeeSchema = JsonSchema.Parse(schemaJson, resolver); + + string json = @"{ + ""name"": ""James"", + ""age"": 29, + ""salary"": 9000.01, + ""jobTitle"": ""Junior Vice President"" + }"; + + JObject employee = JObject.Parse(json); + + bool valid = employee.IsValid(employeeSchema); + + Console.WriteLine(valid); + // true + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/SaveJsonSchemaToFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/SaveJsonSchemaToFile.cs new file mode 100644 index 00000000..b315890d --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/Schema/SaveJsonSchemaToFile.cs @@ -0,0 +1,27 @@ +using Newtonsoft.Json.Schema; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema +{ + public class SaveJsonSchemaToFile + { + public void Example() + { + JsonSchema schema = JsonSchema.Parse(@"{'type': 'object'}"); + + // serialize JsonSchema to a string and then write string to a file + File.WriteAllText(@"c:\schema.json", schema.ToString()); + + // serialize JsonSchema directly to a file + using (StreamWriter file = File.CreateText(@"c:\schema.json")) + using (JsonTextWriter writer = new JsonTextWriter(file)) + { + schema.WriteTo(writer); + } + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeConditionalProperty.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeConditionalProperty.cs new file mode 100644 index 00000000..01410d6b --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/SerializeConditionalProperty.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class SerializeConditionalProperty + { + public class Employee + { + public string Name { get; set; } + public Employee Manager { get; set; } + + public bool ShouldSerializeManager() + { + // don't serialize the Manager property if an employee is their own manager + return (Manager != this); + } + } + + public void Example() + { + Employee joe = new Employee(); + joe.Name = "Joe Employee"; + Employee mike = new Employee(); + mike.Name = "Mike Manager"; + + joe.Manager = mike; + + // mike is his own manager + // ShouldSerialize will skip this property + mike.Manager = mike; + + string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented); + // [ + // { + // "Name": "Joe Employee", + // "Manager": { + // "Name": "Mike Manager" + // } + // }, + // { + // "Name": "Mike Manager" + // } + // ] + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Examples/WriteJsonWithJsonTextWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Examples/WriteJsonWithJsonTextWriter.cs new file mode 100644 index 00000000..d6c40224 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Documentation/Examples/WriteJsonWithJsonTextWriter.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Tests.Documentation.Examples +{ + public class WriteJsonWithJsonTextWriter + { + public void Example() + { + StringBuilder sb = new StringBuilder(); + StringWriter sw = new StringWriter(sb); + + using (JsonWriter writer = new JsonTextWriter(sw)) + { + writer.Formatting = Formatting.Indented; + + writer.WriteStartObject(); + writer.WritePropertyName("CPU"); + writer.WriteValue("Intel"); + writer.WritePropertyName("PSU"); + writer.WriteValue("500W"); + writer.WritePropertyName("Drives"); + writer.WriteStartArray(); + writer.WriteValue("DVD read/writer"); + writer.WriteComment("(broken)"); + writer.WriteValue("500 gigabyte hard drive"); + writer.WriteValue("200 gigabype hard drive"); + writer.WriteEnd(); + writer.WriteEndObject(); + } + + Console.WriteLine(sb.ToString()); + // { + // "CPU": "Intel", + // "PSU": "500W", + // "Drives": [ + // "DVD read/writer" + // /*(broken)*/, + // "500 gigabyte hard drive", + // "200 gigabype hard drive" + // ] + // } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs index 4626449d..b0383d4a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs @@ -306,7 +306,7 @@ namespace Newtonsoft.Json.Tests.Documentation #region LinqToJsonQuerying var postTitles = - from p in rss["channel"]["item"].Children() + from p in rss["channel"]["item"] select (string)p["title"]; foreach (var item in postTitles) diff --git a/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs index f103ec75..7060640e 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs @@ -53,40 +53,40 @@ using System.Globalization; namespace Newtonsoft.Json.Tests.Documentation { + public class LogEventInfo + { + public LogLevel Level; + public string Message; + public Exception Exception; + } + + public class LogLevel + { + public static LogLevel Info; + public static LogLevel Trace; + public static LogLevel Error; + public static LogLevel Warn; + public static LogLevel Off; + } + + public class Logger + { + public void Log(LogEventInfo logEvent) + { + } + } + + public static class LogManager + { + public static Logger GetLogger(string className) + { + return new Logger(); + } + } + [TestFixture] public class TraceWriterTests : TestFixtureBase { - public class LogEventInfo - { - public LogLevel Level; - public string Message; - public Exception Exception; - } - - public class LogLevel - { - public static LogLevel Info; - public static LogLevel Trace; - public static LogLevel Error; - public static LogLevel Warn; - public static LogLevel Off; - } - - public class Logger - { - public void Log(LogEventInfo logEvent) - { - } - } - - public static class LogManager - { - public static Logger GetLogger(string className) - { - return new Logger(); - } - } - #region CustomTraceWriterExample public class NLogTraceWriter : ITraceWriter { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs index bce45527..eefff4f4 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs @@ -45,6 +45,26 @@ namespace Newtonsoft.Json.Tests.Linq [TestFixture] public class JArrayTests : TestFixtureBase { + [Test] + public void RemoveSpecificAndRemoveSelf() + { + JObject o = new JObject + { + {"results", new JArray(1, 2, 3, 4)} + }; + + JArray a = (JArray)o["results"]; + + var last = a.Last(); + + Assert.IsTrue(a.Remove(last)); + + last = a.Last(); + last.Remove(); + + Assert.AreEqual(2, a.Count); + } + [Test] public void Clear() { diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index c0fa665b..f98de600 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -119,9 +119,30 @@ + + + + + + + + + + + + + + + + + + + + + @@ -147,8 +168,10 @@ + + @@ -157,7 +180,7 @@ - + @@ -189,6 +212,7 @@ + diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index d468d0e2..499625dd 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -35,7 +35,7 @@ using System.Globalization; namespace Newtonsoft.Json.Bson { /// - /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. + /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. /// public class BsonWriter : JsonWriter {