From c1ce4c366fb965c6028d0e766c542504e9a54ee1 Mon Sep 17 00:00:00 2001 From: JamesNK Date: Sun, 10 Feb 2008 10:56:19 +0000 Subject: [PATCH] Json.NET 2.0 Beta New feature - LINQ to JSON! New feature - Ability to specify how JsonSerializer handles null values when serializing/deserializing. New feature - Ability to specify how JsonSerializer handles missing values when deserializing. Change - Improved support for reading and writing JavaScript constructors. Change - A new JsonWriter can now write additional tokens without erroring. Bug fix - JsonSerializer handles deserializing dictionaries where the key isn't a string. Bug fix - JsonReader now correctly parses hex character codes. --- .../JsonSerializerTest.cs | 198 +++++++- Src/Newtonsoft.Json.Tests/LinqToJsonTest.cs | 432 ++++++++++++++++++ .../Newtonsoft.Json.Tests.csproj | 23 +- .../Properties/AssemblyInfo.cs | 4 +- .../XmlNodeConverterTest.cs | 2 +- Src/Newtonsoft.Json.sln | 20 +- .../Converters/XmlNodeConverter.cs | 3 - Src/Newtonsoft.Json/JsonReader.cs | 150 ++++-- Src/Newtonsoft.Json/JsonSerializer.cs | 104 +++-- Src/Newtonsoft.Json/JsonToken.cs | 8 +- Src/Newtonsoft.Json/JsonWriter.cs | 62 ++- Src/Newtonsoft.Json/Linq/Extensions.cs | 143 ++++++ Src/Newtonsoft.Json/Linq/JArray.cs | 106 +++++ Src/Newtonsoft.Json/Linq/JConstructor.cs | 92 ++++ Src/Newtonsoft.Json/Linq/JContainer.cs | 290 ++++++++++++ Src/Newtonsoft.Json/Linq/JObject.cs | 133 ++++++ Src/Newtonsoft.Json/Linq/JProperty.cs | 86 ++++ Src/Newtonsoft.Json/Linq/JToken.cs | 415 +++++++++++++++++ Src/Newtonsoft.Json/Linq/JValue.cs | 149 ++++++ Src/Newtonsoft.Json/Linq/JsonTokenType.cs | 48 ++ Src/Newtonsoft.Json/MemberMapping.cs | 25 + .../MemberMappingCollection.cs | 25 + Src/Newtonsoft.Json/MissingMemberHandling.cs | 43 ++ Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 60 ++- Src/Newtonsoft.Json/NullValueHandling.cs | 47 ++ .../Properties/AssemblyInfo.cs | 4 +- Src/Newtonsoft.Json/ReferenceLoopHandling.cs | 50 ++ Src/Newtonsoft.Json/StringBuffer.cs | 8 +- .../Utilities/CollectionUtils.cs | 8 + .../Utilities/ReflectionUtils.cs | 40 +- 30 files changed, 2626 insertions(+), 152 deletions(-) create mode 100644 Src/Newtonsoft.Json.Tests/LinqToJsonTest.cs create mode 100644 Src/Newtonsoft.Json/Linq/Extensions.cs create mode 100644 Src/Newtonsoft.Json/Linq/JArray.cs create mode 100644 Src/Newtonsoft.Json/Linq/JConstructor.cs create mode 100644 Src/Newtonsoft.Json/Linq/JContainer.cs create mode 100644 Src/Newtonsoft.Json/Linq/JObject.cs create mode 100644 Src/Newtonsoft.Json/Linq/JProperty.cs create mode 100644 Src/Newtonsoft.Json/Linq/JToken.cs create mode 100644 Src/Newtonsoft.Json/Linq/JValue.cs create mode 100644 Src/Newtonsoft.Json/Linq/JsonTokenType.cs create mode 100644 Src/Newtonsoft.Json/MissingMemberHandling.cs create mode 100644 Src/Newtonsoft.Json/NullValueHandling.cs create mode 100644 Src/Newtonsoft.Json/ReferenceLoopHandling.cs diff --git a/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs index 26475564..c1361298 100644 --- a/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs @@ -33,6 +33,8 @@ using System.Collections; using System.Xml; using System.Xml.Serialization; using System.Collections.ObjectModel; +using System.Runtime.Serialization.Json; +using System.Net.Mail; namespace Newtonsoft.Json.Tests { @@ -42,6 +44,31 @@ namespace Newtonsoft.Json.Tests public DateTime Expiry; public decimal Price; public string[] Sizes; + + public override bool Equals(object obj) + { + if (obj is Product) + return ((Product)obj).Name == Name; + + return base.Equals(obj); + } + + public override int GetHashCode() + { + return (Name ?? string.Empty).GetHashCode(); + } + } + + public class ProductCollection : List + { + } + + public class ProductShort + { + public string Name; + public DateTime Expiry; + //public decimal Price; + public string[] Sizes; } public class Store @@ -489,7 +516,7 @@ keyword such as type of business."" [Test] public void ReadOnlyCollectionSerialize() { - ReadOnlyCollection r1 = new ReadOnlyCollection(new int[] {0, 1, 2, 3, 4}); + ReadOnlyCollection r1 = new ReadOnlyCollection(new int[] { 0, 1, 2, 3, 4 }); string jsonText = JavaScriptConvert.SerializeObject(r1); @@ -518,32 +545,155 @@ keyword such as type of business."" } } - //public abstract class Foo - //{ - //} + [Test] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not find member 'Price' on object of type 'RuntimeType'")] + public void MissingMemberDeserialize() + { + Product product = new Product(); - //public class Baz : Foo - //{ - //} + product.Name = "Apple"; + product.Expiry = new DateTime(2008, 12, 28); + product.Price = 3.99M; + product.Sizes = new string[] { "Small", "Medium", "Large" }; - //public class Bar : Foo - //{ - //} + string output = JavaScriptConvert.SerializeObject(product); + //{ + // "Name": "Apple", + // "Expiry": new Date(1230422400000), + // "Price": 3.99, + // "Sizes": [ + // "Small", + // "Medium", + // "Large" + // ] + //} - //public class BazJsonConverter : JsonConverter - //{ - // public override bool CanConvert(Type objectType) - // { - // throw new Exception("The method or operation is not implemented."); - // } - //} + ProductShort deserializedProductShort = (ProductShort)JavaScriptConvert.DeserializeObject(output, typeof(ProductShort)); + } - //public class BarJsonConverter : JsonConverter - //{ - // public override bool CanConvert(Type objectType) - // { - // throw new Exception("The method or operation is not implemented."); - // } - //} + [Test] + public void MissingMemberDeserializeOkay() + { + Product product = new Product(); + + product.Name = "Apple"; + product.Expiry = new DateTime(2008, 12, 28); + product.Price = 3.99M; + product.Sizes = new string[] { "Small", "Medium", "Large" }; + + string output = JavaScriptConvert.SerializeObject(product); + //{ + // "Name": "Apple", + // "Expiry": new Date(1230422400000), + // "Price": 3.99, + // "Sizes": [ + // "Small", + // "Medium", + // "Large" + // ] + //} + + JsonSerializer jsonSerializer = new JsonSerializer(); + jsonSerializer.MissingMemberHandling = MissingMemberHandling.Ignore; + + object deserializedValue; + + using (JsonReader jsonReader = new JsonReader(new StringReader(output))) + { + deserializedValue = jsonSerializer.Deserialize(jsonReader, typeof(ProductShort)); + } + + ProductShort deserializedProductShort = (ProductShort)deserializedValue; + + Assert.AreEqual("Apple", deserializedProductShort.Name); + Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProductShort.Expiry); + Assert.AreEqual("Small", deserializedProductShort.Sizes[0]); + Assert.AreEqual("Medium", deserializedProductShort.Sizes[1]); + Assert.AreEqual("Large", deserializedProductShort.Sizes[2]); + } + + [Test] + public void Unicode() + { + string json = @"[""PRE\u003cPOST""]"; + + DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List)); + List dataContractResult = (List)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))); + + List jsonNetResult = JavaScriptConvert.DeserializeObject>(json); + + Assert.AreEqual(1, jsonNetResult.Count); + Assert.AreEqual(dataContractResult[0], jsonNetResult[0]); + } + + [Test] + public void NonStringKeyDictionary() + { + Dictionary values = new Dictionary(); + values.Add(-5, 6); + values.Add(int.MinValue, int.MaxValue); + + string json = JavaScriptConvert.SerializeObject(values); + + Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json); + + Dictionary newValues = JavaScriptConvert.DeserializeObject>(json); + + CollectionAssert.AreEqual(values, newValues); + } + + [Test] + public void AnonymousObjectSerialization() + { + var anonymous = new { StringValue = "I am a string", IntValue = int.MaxValue }; + + string json = JavaScriptConvert.SerializeObject(anonymous); + Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647}", json); + } + + [Test] + public void CustomCollectionSerialization() + { + ProductCollection collection = new ProductCollection() + { + new Product() { Name = "Test1" }, + new Product() { Name = "Test2" }, + new Product() { Name = "Test3" } + }; + + JsonSerializer jsonSerializer = new JsonSerializer(); + jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + StringWriter sw = new StringWriter(); + + jsonSerializer.Serialize(sw, collection); + + Assert.AreEqual(@"[{""Name"":""Test1"",""Expiry"":new Date(-59011459200000),""Price"":0,""Sizes"":null},{""Name"":""Test2"",""Expiry"":new Date(-59011459200000),""Price"":0,""Sizes"":null},{""Name"":""Test3"",""Expiry"":new Date(-59011459200000),""Price"":0,""Sizes"":null}]", + sw.GetStringBuilder().ToString()); + + ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection)); + + CollectionAssert.AreEqual(collection, collectionNew); + } + + [Test] + public void NullValueHandlingSerialization() + { + Store s1 = new Store(); + + JsonSerializer jsonSerializer = new JsonSerializer(); + jsonSerializer.NullValueHandling = NullValueHandling.Ignore; + + StringWriter sw = new StringWriter(); + jsonSerializer.Serialize(sw, s1); + + Assert.AreEqual(@"{""Color"":2,""Establised"":new Date(1264118400000),""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""Expiry"":new Date(949532490000),""Price"":0},{""Name"":""Alien"",""Expiry"":new Date(-59011459200000),""Price"":0}]}", sw.GetStringBuilder().ToString()); + + Store s2 = (Store)jsonSerializer.Deserialize(new JsonReader(new StringReader("{}")), typeof(Store)); + Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", s2.Escape); + + Store s3 = (Store)jsonSerializer.Deserialize(new JsonReader(new StringReader(@"{""Escape"":null}")), typeof(Store)); + Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", s3.Escape); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/LinqToJsonTest.cs b/Src/Newtonsoft.Json.Tests/LinqToJsonTest.cs new file mode 100644 index 00000000..21df18f2 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/LinqToJsonTest.cs @@ -0,0 +1,432 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using Newtonsoft.Json.Linq; +using System.Xml; +using System.IO; + +namespace Newtonsoft.Json.Tests +{ + [TestFixture] + public class LinqToJsonTest + { + [Test] + public void ObjectParse() + { + string json = @"{ + CPU: 'Intel', + Drives: [ + 'DVD read/writer', + ""500 gigabyte hard drive"" + ] +}"; + + JObject o = JObject.Parse(json); + IList properties = o.Properties().ToList(); + + Assert.AreEqual("CPU", properties[0].Name); + Assert.AreEqual("Intel", (string)properties[0].Value); + Assert.AreEqual("Drives", properties[1].Name); + + JArray list = (JArray)properties[1].Value; + Assert.AreEqual(2, list.Children().Count()); + Assert.AreEqual("DVD read/writer", (string)list.Children().ElementAt(0)); + Assert.AreEqual("500 gigabyte hard drive", (string)list.Children().ElementAt(1)); + + List parameterValues = + (from p in o.Properties() + where p.Value is JValue + select ((JValue)p.Value).Value).ToList(); + + Assert.AreEqual(1, parameterValues.Count); + Assert.AreEqual("Intel", parameterValues[0]); + } + + [Test] + public void CreateLongArray() + { + string json = @"[0,1,2,3,4,5,6,7,8,9]"; + + JArray a = JArray.Parse(json); + List list = a.Children().ToList(); + + List expected = new List() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + + CollectionAssert.AreEqual(expected, list); + } + + [Test] + public void GoogleSearchAPI() + { + #region GoogleJson + string json = @"{ + results: + [ + { + GsearchResultClass:""GwebSearch"", + unescapedUrl : ""http://www.google.com/"", + url : ""http://www.google.com/"", + visibleUrl : ""www.google.com"", + cacheUrl : +""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"", + title : ""Google"", + titleNoFormatting : ""Google"", + content : ""Enables users to search the Web, Usenet, and +images. Features include PageRank, caching and translation of +results, and an option to find similar pages."" + }, + { + GsearchResultClass:""GwebSearch"", + unescapedUrl : ""http://news.google.com/"", + url : ""http://news.google.com/"", + visibleUrl : ""news.google.com"", + cacheUrl : +""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"", + title : ""Google News"", + titleNoFormatting : ""Google News"", + content : ""Aggregated headlines and a search engine of many of the world's news sources."" + }, + + { + GsearchResultClass:""GwebSearch"", + unescapedUrl : ""http://groups.google.com/"", + url : ""http://groups.google.com/"", + visibleUrl : ""groups.google.com"", + cacheUrl : +""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"", + title : ""Google Groups"", + titleNoFormatting : ""Google Groups"", + content : ""Enables users to search and browse the Usenet +archives which consist of over 700 million messages, and post new +comments."" + }, + + { + GsearchResultClass:""GwebSearch"", + unescapedUrl : ""http://maps.google.com/"", + url : ""http://maps.google.com/"", + visibleUrl : ""maps.google.com"", + cacheUrl : +""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"", + title : ""Google Maps"", + titleNoFormatting : ""Google Maps"", + content : ""Provides directions, interactive maps, and +satellite/aerial imagery of the United States. Can also search by +keyword such as type of business."" + } + ], + + adResults: + [ + { + GsearchResultClass:""GwebSearch.ad"", + title : ""Gartner Symposium/ITxpo"", + content1 : ""Meet brilliant Gartner IT analysts"", + content2 : ""20-23 May 2007- Barcelona, Spain"", + url : +""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", + + impressionUrl : +""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", + + unescapedUrl : +""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", + + visibleUrl : ""www.gartner.com"" + } + ] +} +"; + #endregion + + JObject o = JObject.Parse(json); + + List resultObjects = o.PropertyValue("results") + .Children().ToList(); + + + List resultUrls = o.PropertyValue("results") + .Children() + .PropertyValues("url") + .ToList(); + + List expectedUrls = new List() { "http://www.google.com/", "http://news.google.com/", "http://groups.google.com/", "http://maps.google.com/" }; + + CollectionAssert.AreEqual(expectedUrls, resultUrls); + + List descendants = o.Descendants().ToList(); + Assert.AreEqual(89, descendants.Count); + } + + [Test] + public void JTokenToString() + { + string json = @"{ + CPU: 'Intel', + Drives: [ + 'DVD read/writer', + ""500 gigabyte hard drive"" + ] +}"; + + JObject o = JObject.Parse(json); + + Assert.AreEqual(@"{ + ""CPU"": ""Intel"", + ""Drives"": [ + ""DVD read/writer"", + ""500 gigabyte hard drive"" + ] +}", o.ToString()); + + JArray list = o.PropertyValue("Drives"); + + Assert.AreEqual(@"[ + ""DVD read/writer"", + ""500 gigabyte hard drive"" +]", list.ToString()); + + JProperty cpuProperty = o.Property("CPU"); + Assert.AreEqual(@"""CPU"": ""Intel""", cpuProperty.ToString()); + + JProperty drivesProperty = o.Property("Drives"); + Assert.AreEqual(@"""Drives"": [ + ""DVD read/writer"", + ""500 gigabyte hard drive"" +]", drivesProperty.ToString()); + } + + [Test] + public void JTokenToStringTypes() + { + string json = @"{""Color"":2,""Establised"":new Date(1264118400000),""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""Expiry"":new Date(949532490000),""Price"":0},{""Name"":""Alien"",""Expiry"":new Date(-59011459200000),""Price"":0}]}"; + + JObject o = JObject.Parse(json); + + Assert.AreEqual(@"""Establised"": new Date(1264118400000)", o.Property("Establised").ToString()); + Assert.AreEqual(@"new Date(1264118400000)", o.Property("Establised").Value.ToString()); + Assert.AreEqual(@"""Width"": 1.1", o.Property("Width").ToString()); + Assert.AreEqual(@"1.1", o.Property("Width").Value.ToString()); + Assert.AreEqual(@"""Open"": false", o.Property("Open").ToString()); + Assert.AreEqual(@"false", o.Property("Open").Value.ToString()); + + json = @"[null,undefined]"; + + JArray a = JArray.Parse(json); + Assert.AreEqual(@"[ + null, + undefined +]", a.ToString()); + Assert.AreEqual(@"null", a.Children().ElementAt(0).ToString()); + Assert.AreEqual(@"undefined", a.Children().ElementAt(1).ToString()); + } + + [Test] + public void CreateJTokenTree() + { + JObject o = + new JObject( + new JProperty("Test1", "Test1Value"), + new JProperty("Test2", "Test2Value"), + new JProperty("Test3", "Test3Value"), + new JProperty("Test4", null) + ); + + Assert.AreEqual(4, o.Properties().Count()); + + Assert.AreEqual(@"{ + ""Test1"": ""Test1Value"", + ""Test2"": ""Test2Value"", + ""Test3"": ""Test3Value"", + ""Test4"": null +}", o.ToString()); + + JArray a = + new JArray( + o, + new DateTime(2000, 10, 10), + 55, + new JArray( + "1", + 2, + 3.0, + new DateTime(4, 5, 6, 7, 8, 9) + ), + new JConstructor( + "ConstructorName", + "param1", + 2, + 3.0 + ) + ); + + Assert.AreEqual(5, a.Count()); + Assert.AreEqual(@"[ + { + ""Test1"": ""Test1Value"", + ""Test2"": ""Test2Value"", + ""Test3"": ""Test3Value"", + ""Test4"": null + }, + new Date(971136000000), + 55, + [ + ""1"", + 2, + 3, + new Date(-59011459200000) + ], + new ConstructorName( + ""param1"", + 2, + 3 + ) +]", a.ToString()); + } + + private 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 new List() + { + new Post() + { + Title = "LINQ to JSON beta", + Description = "Annoucing LINQ to JSON", + Link = "http://james.newtonking.com/projects/json-net.aspx", + Categories = new List() { "Json.NET", "LINQ" } + }, + new Post() + { + 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", + Categories = new List() { "Json.NET", "CodePlex" } + } + }; + } + + [Test] + public void CreateJTokenTreeNested() + { + 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" + // ] + // } + // ] + // } + //} + + var postTitles = + from p in rss.PropertyValue("channel") + .PropertyValue("item") + .Children() + select p.PropertyValue("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.PropertyValue("channel") + .PropertyValue("item") + .Children() + .PropertyValues("category") + .Children() + 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 + } + } +} \ 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 e0da73c4..c66a51ef 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -1,8 +1,8 @@ - + Debug AnyCPU - 8.0.50727 + 9.0.21022 2.0 {3E6E2335-B079-4B5B-A65A-9D586914BCBB} Library @@ -17,6 +17,12 @@ + + + 2.0 + + + v3.5 true @@ -41,7 +47,19 @@ ..\Lib\nunit.framework.dll + + 3.5 + + + 3.0 + + + 3.0 + + + 3.5 + @@ -50,6 +68,7 @@ + diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index 0fc1b845..20cb4f50 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -31,5 +31,5 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.3.0.0")] -[assembly: AssemblyFileVersion("1.3.0.0")] +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] diff --git a/Src/Newtonsoft.Json.Tests/XmlNodeConverterTest.cs b/Src/Newtonsoft.Json.Tests/XmlNodeConverterTest.cs index ac75d3df..21b4bcdb 100644 --- a/Src/Newtonsoft.Json.Tests/XmlNodeConverterTest.cs +++ b/Src/Newtonsoft.Json.Tests/XmlNodeConverterTest.cs @@ -334,7 +334,7 @@ namespace Newtonsoft.Json.Tests XmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText); - string expected = @"2.599true2000-03-30T00:00:00.0000000+12:00"; + string expected = @"2.599true2000-03-30T00:00:00.0000000+13:00"; Assert.AreEqual(expected, newDoc.InnerXml); } diff --git a/Src/Newtonsoft.Json.sln b/Src/Newtonsoft.Json.sln index 9f268d1d..91464170 100644 --- a/Src/Newtonsoft.Json.sln +++ b/Src/Newtonsoft.Json.sln @@ -1,27 +1,15 @@  -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json", "Newtonsoft.Json\Newtonsoft.Json.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection -EndProject +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection ProjectSection(SolutionItems) = preProject Lib\nunit.framework.dll = Lib\nunit.framework.dll Lib\nunit.framework.xml = Lib\nunit.framework.xml EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json", "Newtonsoft.Json\Newtonsoft.Json.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 27758213..3c5a7adb 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -415,9 +415,6 @@ namespace Newtonsoft.Json.Converters DeserializeValue(reader, document, manager, propertyName, currentNode); } break; - //case JsonToken.String: - // DeserializeValue(reader, document, manager, TextName, currentNode); - // break; case JsonToken.EndObject: case JsonToken.EndArray: return; diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index 197da206..db7181e6 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -48,8 +48,8 @@ namespace Newtonsoft.Json Array, Closed, PostValue, + ConstructorStart, Constructor, - ConstructorEnd, Error, Finished } @@ -142,15 +142,16 @@ namespace Newtonsoft.Json private void ParseString(char quote) { bool stringTerminated = false; + bool hexNumber = false; + int hexCount = 0; while (!stringTerminated && MoveNext()) { + if (hexNumber) + hexCount++; + switch (_currentChar) { - //case 0: - //case 0x0A: - //case 0x0D: - // throw new JsonReaderException("Unterminated string"); case '\\': if (MoveNext()) { @@ -172,10 +173,8 @@ namespace Newtonsoft.Json _buffer.Append('\r'); break; case 'u': - //_buffer.Append((char) Integer.parseInt(next(4), 16)); - break; - case 'x': - //_buffer.Append((char) Integer.parseInt(next(2), 16)); + // note the start of a hex character + hexNumber = true; break; default: _buffer.Append(_currentChar); @@ -198,6 +197,19 @@ namespace Newtonsoft.Json _buffer.Append(_currentChar); break; } + + if (hexCount == 4) + { + // remove hex characters from buffer, convert to char and then add + string hexString = _buffer.ToString(_buffer.Position - 4, 4); + char hexChar = Convert.ToChar(int.Parse(hexString, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo)); + + _buffer.Position = _buffer.Position - 4; + _buffer.Append(hexChar); + + hexNumber = false; + hexCount = 0; + } } if (!stringTerminated) @@ -273,6 +285,8 @@ namespace Newtonsoft.Json case State.Property: case State.Array: case State.ArrayStart: + case State.Constructor: + case State.ConstructorStart: return ParseValue(); case State.Complete: break; @@ -309,6 +323,10 @@ namespace Newtonsoft.Json SetToken(JsonToken.EndArray); ClearCurrentChar(); return true; + case ')': + SetToken(JsonToken.EndConstructor); + ClearCurrentChar(); + return true; case '/': ParseComment(); return true; @@ -458,6 +476,11 @@ namespace Newtonsoft.Json Push(JsonType.Array); ClearCurrentChar(); break; + case JsonToken.StartConstructor: + _currentState = State.ConstructorStart; + Push(JsonType.Constructor); + ClearCurrentChar(); + break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); ClearCurrentChar(); @@ -468,6 +491,11 @@ namespace Newtonsoft.Json ClearCurrentChar(); _currentState = State.PostValue; break; + case JsonToken.EndConstructor: + ValidateEnd(JsonToken.EndConstructor); + ClearCurrentChar(); + _currentState = State.PostValue; + break; case JsonToken.PropertyName: _currentState = State.Property; ClearCurrentChar(); @@ -477,7 +505,6 @@ namespace Newtonsoft.Json case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: - case JsonToken.Constructor: case JsonToken.Date: _currentState = State.PostValue; break; @@ -551,15 +578,17 @@ namespace Newtonsoft.Json //ClearCurrentChar(); return true; case ')': - if (_currentState == State.Constructor) - { - _currentState = State.ConstructorEnd; - return false; - } - else - { - throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar); - } + SetToken(JsonToken.EndConstructor); + return true; + //if (_currentState == State.Constructor) + //{ + // _currentState = State.ConstructorEnd; + // return false; + //} + //else + //{ + // throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar); + //} default: if (char.IsWhiteSpace(_currentChar)) { @@ -605,44 +634,69 @@ namespace Newtonsoft.Json MoveNext(); } - string constructorName = _buffer.ToString(); - _buffer.Position = 0; - - List parameters = new List(); EatWhitespace(false); - if (_currentChar == '(' && MoveNext()) - { - _currentState = State.Constructor; + if (_currentChar != '(') + throw new JsonReaderException("Unexpected character while parsing constructor: " + _currentChar); - while (ParseValue()) + string constructorName = _buffer.ToString(); + _buffer.Position = 0; + + SetToken(JsonToken.StartConstructor); + + _value = constructorName; + _valueType = typeof(string); + + if (string.CompareOrdinal(constructorName, "Date") == 0) + { + IList parameters = new List(); + + MoveNext(); + while (ParseValue() && _token != JsonToken.EndConstructor) { parameters.Add(_value); - _currentState = State.Constructor; } - if (string.CompareOrdinal(constructorName, "Date") == 0) - { - long javaScriptTicks = Convert.ToInt64(parameters[0]); + long javaScriptTicks = Convert.ToInt64(parameters[0]); - DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks); + DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks); - SetToken(JsonToken.Date, date); - } - else - { - JavaScriptConstructor constructor = new JavaScriptConstructor(constructorName, new JavaScriptParameters(parameters)); - - if (_currentState == State.ConstructorEnd) - { - SetToken(JsonToken.Constructor, constructor); - } - } - - // move past ')' - MoveNext(); + SetToken(JsonToken.Date, date); } + + + + //{ + // _currentState = State.Constructor; + + // while (ParseValue()) + // { + // parameters.Add(_value); + // _currentState = State.Constructor; + // } + + // if (string.CompareOrdinal(constructorName, "Date") == 0) + // { + // long javaScriptTicks = Convert.ToInt64(parameters[0]); + + // DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks); + + // SetToken(JsonToken.Date, date); + // } + // else + // { + // JavaScriptConstructor constructor = new JavaScriptConstructor(constructorName, new JavaScriptParameters(parameters)); + + // if (_currentState == State.ConstructorEnd) + // { + // SetToken(JsonToken.Constructor, constructor); + // } + // } + + // // move past ')' + // MoveNext(); + //} } } } @@ -716,6 +770,8 @@ namespace Newtonsoft.Json return JsonType.Object; case JsonToken.EndArray: return JsonType.Array; + case JsonToken.EndConstructor: + return JsonType.Constructor; default: throw new JsonReaderException("Not a valid close JsonToken: " + token); } @@ -803,7 +859,7 @@ namespace Newtonsoft.Json // check next character to see if start of a comment return (HasNext() && PeekNext() == '*'); case ')': - if (_currentState == State.Constructor) + if (_currentState == State.Constructor || _currentState == State.ConstructorStart) return true; break; default: diff --git a/Src/Newtonsoft.Json/JsonSerializer.cs b/Src/Newtonsoft.Json/JsonSerializer.cs index 43dabb3d..55243ed4 100644 --- a/Src/Newtonsoft.Json/JsonSerializer.cs +++ b/Src/Newtonsoft.Json/JsonSerializer.cs @@ -35,25 +35,6 @@ using System.Globalization; namespace Newtonsoft.Json { - /// - /// Specifies reference loop handling options for the . - /// - public enum ReferenceLoopHandling - { - /// - /// Throw a when a loop is encountered. - /// - Error = 0, - /// - /// Ignore loop references and do not serialize. - /// - Ignore = 1, - /// - /// Serialize loop references. - /// - Serialize = 2 - } - /// /// Serializes and deserializes objects into and from the Json format. /// The enables you to control how objects are encoded into Json. @@ -61,6 +42,8 @@ namespace Newtonsoft.Json public class JsonSerializer { private ReferenceLoopHandling _referenceLoopHandling; + private MissingMemberHandling _missingMemberHandling; + private NullValueHandling _nullValueHandling; private int _level; private JsonConverterCollection _converters; private Dictionary _typeMemberMappings; @@ -74,13 +57,42 @@ namespace Newtonsoft.Json set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) - { throw new ArgumentOutOfRangeException("value"); - } + _referenceLoopHandling = value; } } + /// + /// Get or set how missing members are handled during deserialization. + /// + public MissingMemberHandling MissingMemberHandling + { + get { return _missingMemberHandling; } + set + { + if (value < MissingMemberHandling.Error || value > MissingMemberHandling.Ignore) + throw new ArgumentOutOfRangeException("value"); + + _missingMemberHandling = value; + } + } + + /// + /// Get or set how null values are handled. + /// + public NullValueHandling NullValueHandling + { + get { return _nullValueHandling; } + set + { + if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) + throw new ArgumentOutOfRangeException("value"); + + _nullValueHandling = value; + } + } + public JsonConverterCollection Converters { get @@ -98,6 +110,7 @@ namespace Newtonsoft.Json public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; + _missingMemberHandling = MissingMemberHandling.Error; } #region Deserialize @@ -216,15 +229,22 @@ namespace Newtonsoft.Json case JsonToken.Date: value = EnsureType(reader.Value, objectType); break; - case JsonToken.Constructor: - value = reader.Value.ToString(); + case JsonToken.StartConstructor: + case JsonToken.EndConstructor: + string constructorName = reader.Value.ToString(); + + //if (string.CompareOrdinal(constructorName, "Date") == 0) + // value = CreateDate(reader); + //else + //TODO: use objectType plus constructor arguments to instantiate object + value = constructorName; break; case JsonToken.Null: case JsonToken.Undefined: value = null; break; default: - throw new JsonSerializationException("Unexpected token whil deserializing object: " + reader.TokenType); + throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } @@ -233,6 +253,25 @@ namespace Newtonsoft.Json return value; } + private DateTime CreateDate(JsonReader reader) + { + // move to parameter + if (!reader.Read()) + throw new JsonSerializationException("Unexpected end while creating date."); + + //TODO: add support for Date constructor with multiple arguments + long ticks = Convert.ToInt64(reader.Value); + DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(ticks); + + // move to constructor end + if (!reader.Read()) + throw new JsonSerializationException("Unexpected end while creating date."); + if (reader.TokenType != JsonToken.EndConstructor) + throw new JsonSerializationException("Unexpected token while creating date: " + reader.TokenType); + + return date; + } + private object EnsureType(object value, Type targetType) { // do something about null value when the targetType is a valuetype? @@ -342,20 +381,26 @@ namespace Newtonsoft.Json value = GetObject(reader, memberType); + if (_nullValueHandling == NullValueHandling.Ignore && value == null) + return; + ReflectionUtils.SetMemberValue(memberMapping.Member, target, value); } else if (typeof(IDictionary).IsAssignableFrom(targetType)) { // attempt to get the IDictionary's type - memberType = ReflectionUtils.GetDictionaryValueType(target.GetType()); - + memberType = ReflectionUtils.GetDictionaryValueType(targetType); value = GetObject(reader, memberType); - ((IDictionary)target).Add(memberName, value); + Type keyType = ReflectionUtils.GetDictionaryKeyType(targetType); + object keyValue = EnsureType(memberName, keyType); + + ((IDictionary)target).Add(keyValue, value); } else { - throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name)); + if (_missingMemberHandling == MissingMemberHandling.Error) + throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name)); } } @@ -557,6 +602,9 @@ namespace Newtonsoft.Json { object memberValue = ReflectionUtils.GetMemberValue(member, value); + if (_nullValueHandling == NullValueHandling.Ignore && memberValue == null) + return; + if (writer.SerializeStack.IndexOf(memberValue) != -1) { switch (_referenceLoopHandling) diff --git a/Src/Newtonsoft.Json/JsonToken.cs b/Src/Newtonsoft.Json/JsonToken.cs index e64d8758..fc27644b 100644 --- a/Src/Newtonsoft.Json/JsonToken.cs +++ b/Src/Newtonsoft.Json/JsonToken.cs @@ -49,6 +49,10 @@ namespace Newtonsoft.Json /// /// An object property name. /// + StartConstructor, + /// + /// A constructor end token. + /// PropertyName, /// /// A comment. @@ -87,9 +91,9 @@ namespace Newtonsoft.Json /// EndArray, /// - /// A JavaScript object constructor. + /// A constructor start token. /// - Constructor, + EndConstructor, /// /// A Date. /// diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index 499aa721..953f198b 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -36,6 +36,7 @@ namespace Newtonsoft.Json { Object, Array, + Constructor, None } @@ -63,6 +64,10 @@ namespace Newtonsoft.Json /// Array, /// + /// A constructor is being written. + /// + Constructor, + /// /// A property is being written. /// Property, @@ -100,20 +105,23 @@ namespace Newtonsoft.Json Object, ArrayStart, Array, + ConstructorStart, + Constructor, Closed, Error } // array that gives a new state based on the current state an the token being written private static readonly State[,] stateArray = { - // Start PropertyName ObjectStart Object ArrayStart Array Closed Error - // - /* None */{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, - /* StartObject */{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, - /* StartArray */{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, - /* StartProperty */{ State.Error, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error }, - /* Comment */{ State.Error, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Error, State.Error }, - /* Value */{ State.Error, State.Object, State.Error, State.Error, State.Array, State.Array, State.Error, State.Error }, +// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error +// +/* None */{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, +/* StartObject */{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, +/* StartArray */{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, +/* StartConstructor */{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, +/* StartProperty */{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, +/* Comment */{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, +/* Value */{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, }; private int _top; @@ -157,6 +165,9 @@ namespace Newtonsoft.Json case State.Array: case State.ArrayStart: return WriteState.Array; + case State.Constructor: + case State.ConstructorStart: + return WriteState.Constructor; case State.Property: return WriteState.Property; case State.Start: @@ -322,6 +333,20 @@ namespace Newtonsoft.Json AutoCompleteClose(JsonToken.EndArray); } + public void WriteStartConstructor(string name) + { + AutoComplete(JsonToken.StartConstructor); + Push(JsonType.Constructor); + _writer.Write("new "); + _writer.Write(name); + _writer.Write("("); + } + + public void WriteEndConstructor() + { + AutoCompleteClose(JsonToken.EndConstructor); + } + /// /// Writes the property name of a name/value pair on a Json object. /// @@ -360,6 +385,9 @@ namespace Newtonsoft.Json case JsonType.Array: WriteEndArray(); break; + case JsonType.Constructor: + WriteEndConstructor(); + break; default: throw new JsonWriterException("Unexpected type when writing end: " + type); } @@ -381,6 +409,8 @@ namespace Newtonsoft.Json return JsonType.Object; case JsonToken.EndArray: return JsonType.Array; + case JsonToken.EndConstructor: + return JsonType.Constructor; default: throw new JsonWriterException("No type for token: " + token); } @@ -394,6 +424,8 @@ namespace Newtonsoft.Json return JsonToken.EndObject; case JsonType.Array: return JsonToken.EndArray; + case JsonType.Constructor: + return JsonToken.EndConstructor; default: throw new JsonWriterException("No close token for type: " + type); } @@ -434,6 +466,9 @@ namespace Newtonsoft.Json case JsonToken.EndArray: _writer.Write("]"); break; + case JsonToken.EndConstructor: + _writer.Write(")"); + break; default: throw new JsonWriterException("Invalid JsonToken: " + token); } @@ -491,7 +526,7 @@ namespace Newtonsoft.Json case JsonToken.Undefined: case JsonToken.Date: // a value is being written - token = 5; + token = 6; break; } @@ -501,7 +536,7 @@ namespace Newtonsoft.Json if (newState == State.Error) throw new JsonWriterException(string.Format("Token {0} in state {1} would result in an invalid JavaScript object.", tokenBeingWritten.ToString(), _currentState.ToString())); - if ((_currentState == State.Object || _currentState == State.Array) && tokenBeingWritten != JsonToken.Comment) + if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { _writer.Write(','); } @@ -511,8 +546,9 @@ namespace Newtonsoft.Json _writer.Write(' '); } - if (tokenBeingWritten == JsonToken.PropertyName || - (WriteState == WriteState.Array)) + // don't indent a property when it is the first token to be written (i.e. at the start) + if ((tokenBeingWritten == JsonToken.PropertyName && WriteState != WriteState.Start) || + WriteState == WriteState.Array || WriteState == WriteState.Constructor) { WriteIndent(); } @@ -729,4 +765,4 @@ namespace Newtonsoft.Json Close(); } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/Extensions.cs b/Src/Newtonsoft.Json/Linq/Extensions.cs new file mode 100644 index 00000000..0c7e7482 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/Extensions.cs @@ -0,0 +1,143 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Utilities; +using System.Collections; + +namespace Newtonsoft.Json.Linq +{ + public static class Extensions + { + public static IEnumerable Ancestors(this IEnumerable source) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, "source"); + + return source.SelectMany(j => j.Ancestors()); + } + + //TODO + //public static IEnumerable AncestorsAndSelf(this IEnumerable source) where T : JObject + //{ + // ValidationUtils.ArgumentNotNull(source, "source"); + + // return source.SelectMany(j => j.AncestorsAndSelf()); + //} + + public static IEnumerable Descendants(this IEnumerable source) where T : JContainer + { + ValidationUtils.ArgumentNotNull(source, "source"); + + return source.SelectMany(j => j.Descendants()); + } + + //TODO + //public static IEnumerable DescendantsAndSelf(this IEnumerable source) where T : JContainer + //{ + // ValidationUtils.ArgumentNotNull(source, "source"); + + // return source.SelectMany(j => j.DescendantsAndSelf()); + //} + + public static IEnumerable Properties(this IEnumerable source) + { + ValidationUtils.ArgumentNotNull(source, "source"); + + return source.SelectMany(d => d.Properties()); + } + + public static IEnumerable PropertyValues(this IEnumerable source, string name) + { + ValidationUtils.ArgumentNotNull(source, "source"); + + return source.SelectMany(d => d.Properties()) + .Where(p => string.Compare(p.Name, name, StringComparison.Ordinal) == 0) + .Select(p => p.Value) + .Convert(); + } + + //TODO + //public static IEnumerable InDocumentOrder(this IEnumerable source) where T : JObject; + + public static IEnumerable Children(this IEnumerable source) where T : JContainer + { + ValidationUtils.ArgumentNotNull(source, "source"); + + return source.SelectMany(c => c.Children()); + } + + public static IEnumerable Children(this IEnumerable source) + { + ValidationUtils.ArgumentNotNull(source, "source"); + + return source.SelectMany(c => c.Children()).Convert(); + } + + internal static IEnumerable Convert(this IEnumerable source) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, "source"); + + bool cast = typeof(JToken).IsAssignableFrom(typeof(U)); + + foreach (JToken token in source) + { + yield return Convert(token, cast); + } + } + + internal static U Convert(this T token) where T : JToken + { + bool cast = typeof(JToken).IsAssignableFrom(typeof(U)); + + return Convert(token, cast); + } + + internal static U Convert(this T token, bool cast) where T : JToken + { + if (cast) + { + // HACK + return (U)(object)token; + } + else + { + JValue value = token as JValue; + if (value == null) + throw new InvalidCastException(string.Format("Cannot cast {0} to {1}.", token.GetType(), typeof(T))); + + return (U)System.Convert.ChangeType(value.Value, typeof(U)); + } + } + + + //TODO + //public static void Remove(this IEnumerable source) where T : JContainer; + + + } +} diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs new file mode 100644 index 00000000..34800436 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -0,0 +1,106 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Utilities; +using System.IO; + +namespace Newtonsoft.Json.Linq +{ + public class JArray : JContainer + { + public override JsonTokenType Type + { + get { return JsonTokenType.Array; } + } + + public JArray(params object[] content) : this((object)content) + { + } + + public JArray(object content) + { + Add(content); + } + + public int Count() + { + return Children().Count(); + } + + public static JArray Load(JsonReader reader) + { + if (reader.TokenType == JsonToken.None) + { + if (!reader.Read()) + throw new Exception("Error reading JArray from JsonReader."); + } + if (reader.TokenType != JsonToken.StartArray) + { + throw new Exception("Current JsonReader item is not an object."); + } + else + { + if (!reader.Read()) + throw new Exception("Error reading JArray from JsonReader."); + } + + JArray a = new JArray(); + a.ReadContentFrom(reader); + + return a; + } + + public static JArray Parse(string json) + { + JsonReader jsonReader = new JsonReader(new StringReader(json)); + + return Load(jsonReader); + } + + internal override void ValidateObject(JToken o, JToken previous) + { + ValidationUtils.ArgumentNotNull(o, "o"); + + if (o.Type == JsonTokenType.Property) + throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type)); + } + + public override void WriteTo(JsonWriter writer) + { + writer.WriteStartArray(); + + foreach (JToken token in Children()) + { + token.WriteTo(writer); + } + + writer.WriteEndArray(); + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs new file mode 100644 index 00000000..7ab72d87 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -0,0 +1,92 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public class JConstructor : JContainer + { + private string _name; + + public string Name + { + get { return _name; } + set { _name = value; } + } + + public override JsonTokenType Type + { + get { return JsonTokenType.Constructor; } + } + + public JConstructor() + { + } + + public JConstructor(string name, params object[] content) + : this(name, (object)content) + { + } + + public JConstructor(string name, object content) + : this(name) + { + Add(content); + } + + public JConstructor(string name) + { + _name = name; + } + + internal override void ValidateObject(JToken o, JToken previous) + { + ValidationUtils.ArgumentNotNull(o, "o"); + + switch (o.Type) + { + case JsonTokenType.Property: + throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type)); + } + } + + public override void WriteTo(JsonWriter writer) + { + writer.WriteStartConstructor(_name); + + foreach (JToken token in Children()) + { + token.WriteTo(writer); + } + + writer.WriteEndConstructor(); + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs new file mode 100644 index 00000000..11c1b3f1 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -0,0 +1,290 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Utilities; +using System.Collections; + +namespace Newtonsoft.Json.Linq +{ + public abstract class JContainer : JToken + { + private JToken _content; + + internal JToken Content + { + get { return _content; } + set { _content = value; } + } + + public JToken First + { + get + { + if (Last == null) + return null; + + return Last.Next; + } + } + + public JToken Last + { + get { return _content; } + } + + public IEnumerable Children() + { + JToken first = First; + JToken current = first; + if (current == null) + yield break; + + do + { + yield return current; + } while ((current = current.Next) != first); + } + + public IEnumerable Children() + { + return Children().Convert(); + } + + public IEnumerable Descendants() + { + foreach (JToken o in Children()) + { + yield return o; + JContainer c = o as JContainer; + if (c != null) + { + foreach (JToken d in c.Descendants()) + { + yield return d; + } + } + } + } + + public virtual void Add(object content) + { + if (content is IEnumerable && !(content is string)) + { + IEnumerable enumerable = content as IEnumerable; + foreach (object c in enumerable) + { + Add(c); + } + } + else + { + JToken o = CreateFromContent(content); + + JToken last = Last; + JToken next = First ?? o; + + o.Parent = this; + o.Next = next; + + if (last != null) + last.Next = o; + _content = o; + } + } + + public void AddFirst(object content) + { + JToken o = CreateFromContent(content); + + JToken last = Parent.Last; + + o.Parent = Parent; + o.Next = last.Next; + + last.Next = o; + } + + protected JToken CreateFromContent(object content) + { + if (content is JToken) + return (JToken)content; + + return new JValue(content); + } + + public JsonWriter CreateWriter() + { + return null; + } + + public void ReplaceAll(object content) + { + RemoveAll(); + Add(content); + } + + public void RemoveAll() + { + while (_content != null) + { + JToken o = _content; + + JToken next = o.Next; + if (o != _content || next != o.Next) + throw new InvalidOperationException("This operation was corrupted by external code."); + + if (next != o) + o.Next = next.Next; + else + _content = null; + + next.Parent = null; + next.Next = null; + } + } + + internal void Remove(JToken o) + { + if (o.Parent != this) + throw new InvalidOperationException("This operation was corrupted by external code."); + + JToken content = _content; + + while (_content.Next != o) + { + content = content.Next; + } + if (content == o) + { + _content = null; + } + else + { + if (_content == o) + { + _content = content; + } + content.Next = o.Next; + } + o.Parent = null; + o.Next = null; + } + + internal abstract void ValidateObject(JToken o, JToken previous); + + internal void AddObjectSkipNotify(JToken o) + { + ValidateObject(o, this); + + Add(o); + } + + internal void ReadContentFrom(JsonReader r) + { + ValidationUtils.ArgumentNotNull(r, "r"); + + JContainer parent = this; + + do + { + if (parent is JProperty) + { + if (((JProperty)parent).Value != null) + parent = parent.Parent; + } + + switch (r.TokenType) + { + case JsonToken.None: + // new reader. move to actual content + break; + case JsonToken.StartArray: + JArray a = new JArray(); + parent.AddObjectSkipNotify(a); + parent = a; + break; + + case JsonToken.EndArray: + if (parent == this) + return; + + parent = parent.Parent; + break; + case JsonToken.StartObject: + JObject o = new JObject(); + parent.AddObjectSkipNotify(o); + parent = o; + break; + case JsonToken.EndObject: + if (parent == this) + return; + + parent = parent.Parent; + break; + case JsonToken.StartConstructor: + JConstructor constructor = new JConstructor(); + constructor.Name = r.Value.ToString(); + parent.AddObjectSkipNotify(constructor); + parent = constructor; + break; + case JsonToken.EndConstructor: + if (parent == this) + return; + + parent = parent.Parent; + break; + case JsonToken.String: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Date: + case JsonToken.Boolean: + parent.AddObjectSkipNotify(new JValue(r.Value)); + break; + case JsonToken.Comment: + parent.AddObjectSkipNotify(JValue.CreateComment(r.Value.ToString())); + break; + case JsonToken.Null: + parent.AddObjectSkipNotify(JValue.Null); + break; + case JsonToken.Undefined: + parent.AddObjectSkipNotify(JValue.Undefined); + break; + case JsonToken.PropertyName: + JProperty property = new JProperty(r.Value.ToString()); + parent.AddObjectSkipNotify(property); + parent = property; + break; + default: + throw new InvalidOperationException(string.Format("The JsonReader should not be on a token of type {0}.", r.TokenType)); + } + } + while (r.Read()); + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs new file mode 100644 index 00000000..5bcd9079 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -0,0 +1,133 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public class JObject : JContainer + { + public JObject() + { + } + + public JObject(params object[] content) : this((object)content) + { + } + + public JObject(object content) + { + Add(content); + } + + public override JsonTokenType Type + { + get { return JsonTokenType.Object; } + } + + public IEnumerable Properties() + { + return Children().Cast(); + } + + public JProperty Property(string name) + { + return Properties() + .Where(p => string.Compare(p.Name, name, StringComparison.Ordinal) == 0) + .SingleOrDefault(); + } + + public IEnumerable PropertyValues() + { + return Properties().Select(p => p.Value); + } + + public T PropertyValue(string name) + { + JProperty property = Property(name); + + if (property == null) + throw new Exception(string.Format("Property '{0}' does not exist in JSON object.", name)); + + // HACK + return Extensions.Convert(property.Value); + } + + public static JObject Load(JsonReader reader) + { + if (reader.TokenType == JsonToken.None) + { + if (!reader.Read()) + throw new Exception("Error reading JObject from JsonReader."); + } + if (reader.TokenType != JsonToken.StartObject) + { + throw new Exception("Current JsonReader item is not an object."); + } + else + { + if (!reader.Read()) + throw new Exception("Error reading JObject from JsonReader."); + } + + JObject o = new JObject(); + o.ReadContentFrom(reader); + + return o; + } + + public static JObject Parse(string json) + { + JsonReader jsonReader = new JsonReader(new StringReader(json)); + + return Load(jsonReader); + } + + internal override void ValidateObject(JToken o, JToken previous) + { + ValidationUtils.ArgumentNotNull(o, "o"); + + if (o.Type != JsonTokenType.Property) + throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type)); + } + + public override void WriteTo(JsonWriter writer) + { + writer.WriteStartObject(); + + foreach (JProperty property in Properties()) + { + property.WriteTo(writer); + } + + writer.WriteEndObject(); + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs new file mode 100644 index 00000000..ed1080b5 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -0,0 +1,86 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public class JProperty : JContainer + { + private readonly string _name; + + public string Name + { + get { return _name; } + } + + public JToken Value + { + get { return Last; } + set + { + ReplaceAll(value); + } + } + + public override JsonTokenType Type + { + get { return JsonTokenType.Property; } + } + + public JProperty(string name) + { + ValidationUtils.ArgumentNotNullOrEmpty(name, "name"); + + _name = name; + } + + public JProperty(string name, object value) + { + ValidationUtils.ArgumentNotNullOrEmpty(name, "name"); + + _name = name; + Value = CreateFromContent(value); + } + + internal override void ValidateObject(JToken o, JToken previous) + { + ValidationUtils.ArgumentNotNull(o, "o"); + + if (o.Type == JsonTokenType.Property) + throw new ArgumentException(string.Format("An item of type {0} cannot be added to content.", o.Type)); + } + + public override void WriteTo(JsonWriter writer) + { + writer.WritePropertyName(_name); + Value.WriteTo(writer); + } + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs new file mode 100644 index 00000000..9dd5f1fb --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -0,0 +1,415 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; + +namespace Newtonsoft.Json.Linq +{ + public abstract class JToken + { + private JContainer _parent; + private JToken _next; + + public JContainer Parent + { + get { return _parent; } + internal set { _parent = value; } + } + + public JToken Root + { + get { return null; } + } + + public abstract JsonTokenType Type { get; } + + public JToken Next + { + get + { + if (_parent == null) + return null; + + return _next; + } + internal set { _next = value; } + } + + public JToken Previous + { + get + { + if (_parent == null) + return null; + + JToken parentNext = ((JToken) _parent.Content).Next; + JToken parentNextBefore = null; + while (parentNext != this) + { + parentNextBefore = parentNext; + parentNext = parentNext.Next; + } + return parentNextBefore; + } + } + + public bool HasValues + { + get { return false; } + } + + public IEnumerable Ancestors() + { + for (JToken parent = Parent; parent != null; parent = parent.Parent) + { + yield return parent; + } + } + + public IEnumerable AfterSelf() + { + if (Parent == null) + yield break; + + for (JToken o = Next; o != null; o = o.Next) + yield return o; + } + + public IEnumerable BeforeSelf() + { + for (JToken o = Parent.First; o != this; o = o.Next) + yield return o; + } + + //public IEnumerable ObjectsAfterSelf() + //{ + // return null; + //} + + //public IEnumerable ObjectsBeforeSelf() + //{ + // return null; + //} + + public void Remove() + { + if (_parent == null) + throw new InvalidOperationException("The parent is missing."); + + _parent.Remove(this); + } + + public void Replace(JToken value) + { + } + + public abstract void WriteTo(JsonWriter writer); + + public override string ToString() + { + using (StringWriter sw = new StringWriter()) + { + JsonWriter jw = new JsonWriter(sw); + jw.Formatting = Formatting.Indented; + + WriteTo(jw); + + return sw.ToString(); + } + } + + private static JValue EnsureValue(JToken value) + { + if (value == null) + throw new ArgumentNullException("value"); + + if (value is JProperty) + value = ((JProperty)value).Value; + + JValue v = value as JValue; + + return v; + } + + private static bool IsNullable(JToken o) + { + return (o.Type == JsonTokenType.Undefined || o.Type == JsonTokenType.Null); + } + + private static bool ValidateFloat(JToken o, bool nullable) + { + return (o.Type == JsonTokenType.Float || o.Type == JsonTokenType.Integer || (nullable && IsNullable(o))); + } + + private static bool ValidateInteger(JToken o, bool nullable) + { + return (o.Type == JsonTokenType.Integer || (nullable && IsNullable(o))); + } + + private static bool ValidateDate(JToken o, bool nullable) + { + return (o.Type == JsonTokenType.Date || (nullable && IsNullable(o))); + } + + private static bool ValidateBoolean(JToken o, bool nullable) + { + return (o.Type == JsonTokenType.Boolean || (nullable && IsNullable(o))); + } + + private static bool ValidateString(JToken o) + { + return (o.Type == JsonTokenType.String || IsNullable(o)); + } + + #region Cast operators + public static explicit operator bool(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateBoolean(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to Boolean.", v.Type)); + + return (bool)v.Value; + } + + public static explicit operator DateTimeOffset(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateDate(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to DateTimeOffset.", v.Type)); + + return (DateTimeOffset)v.Value; + } + + public static explicit operator bool?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateBoolean(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to Boolean.", v.Type)); + + return (bool?)v.Value; + } + + public static explicit operator long(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to Int64.", v.Type)); + + return (long)v.Value; + } + + public static explicit operator DateTime?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateDate(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to DateTime.", v.Type)); + + return (DateTime?)v.Value; + } + + public static explicit operator DateTimeOffset?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateDate(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to DateTimeOffset.", v.Type)); + + return (DateTimeOffset?)v.Value; + } + + public static explicit operator decimal?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateFloat(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to Decimal.", v.Type)); + + return (decimal?)v.Value; + } + + public static explicit operator double?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateFloat(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to Double.", v.Type)); + + return (double?)v.Value; + } + + public static explicit operator int(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to Int32.", v.Type)); + + return Convert.ToInt32(v.Value); + } + + public static explicit operator int?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to Int32.", v.Type)); + + return (v.Value != null) ? (int?)Convert.ToInt32(v.Value) : null; + } + + public static explicit operator DateTime(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateDate(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to DateTime.", v.Type)); + + return (DateTime)v.Value; + } + + public static explicit operator long?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to Int64.", v.Type)); + + return (long?)v.Value; + } + + public static explicit operator float?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateFloat(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to Single.", v.Type)); + + return (float?)v.Value; + } + + public static explicit operator decimal(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateFloat(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to Decimal.", v.Type)); + + return (decimal)v.Value; + } + + public static explicit operator uint?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to UInt32.", v.Type)); + + return (uint?)v.Value; + } + + public static explicit operator ulong?(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, true)) + throw new ArgumentException(string.Format("Can not convert {0} to UInt64.", v.Type)); + + return (ulong?)v.Value; + } + + public static explicit operator double(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateFloat(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to Double.", v.Type)); + + return (double)v.Value; + } + + public static explicit operator float(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateFloat(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to Single.", v.Type)); + + return (float)v.Value; + } + + public static explicit operator string(JToken value) + { + if (value == null) + return null; + + JValue v = EnsureValue(value); + if (v == null || !ValidateString(v)) + throw new ArgumentException(string.Format("Can not convert {0} to String.", v.Type)); + + return (string)v.Value; + } + + public static explicit operator uint(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to UInt32.", v.Type)); + + return (uint)v.Value; + } + + public static explicit operator ulong(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateInteger(v, false)) + throw new ArgumentException(string.Format("Can not convert {0} to UInt64.", v.Type)); + + return (ulong)v.Value; + } + #endregion + + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs new file mode 100644 index 00000000..e5cbce05 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -0,0 +1,149 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Linq +{ + public class JValue : JToken + { + private JsonTokenType _valueType; + private object _value; + + public static readonly JValue Null = new JValue(null, JsonTokenType.Null); + public static readonly JValue Undefined = new JValue(null, JsonTokenType.Undefined); + + private JValue(object value, JsonTokenType type) + { + _value = value; + _valueType = type; + } + + public JValue(long value) + : this(value, JsonTokenType.Integer) + { + } + + public JValue(double value) + : this(value, JsonTokenType.Float) + { + } + + public JValue(DateTime value) + : this(value, JsonTokenType.Date) + { + } + + public JValue(bool value) + : this(value, JsonTokenType.Boolean) + { + } + + public JValue(string value) + : this(value, JsonTokenType.String) + { + } + + public JValue(object value) : this(value, GetValueType(value)) + { + } + + public static JValue CreateComment(string value) + { + return new JValue(value, JsonTokenType.Comment); + } + + private static JsonTokenType GetValueType(object value) + { + if (value == null) + return JsonTokenType.Null; + else if (value is string) + return JsonTokenType.String; + else if (value is long || value is int || value is short + || value is ulong || value is uint || value is ushort) + return JsonTokenType.Integer; + else if (value is double || value is float) + return JsonTokenType.Float; + else if (value is DateTime) + return JsonTokenType.Date; + else if (value is bool) + return JsonTokenType.Boolean; + + throw new ArgumentException(string.Format("Could not determin JSON object type for type {0}.", value.GetType())); + } + + public override JsonTokenType Type + { + get { return _valueType; } + } + + public object Value + { + get { return _value; } + set { _value = value; } + } + + public static JToken CreateString(string value) + { + return new JValue(value, JsonTokenType.String); + } + + public override void WriteTo(JsonWriter writer) + { + switch (_valueType) + { + case JsonTokenType.Comment: + writer.WriteComment(_value.ToString()); + break; + case JsonTokenType.Integer: + writer.WriteValue(Convert.ToInt64(_value)); + break; + case JsonTokenType.Float: + writer.WriteValue(Convert.ToDouble(_value)); + break; + case JsonTokenType.String: + writer.WriteValue(_value.ToString()); + break; + case JsonTokenType.Boolean: + writer.WriteValue(Convert.ToBoolean(_value)); + break; + case JsonTokenType.Null: + writer.WriteNull(); + break; + case JsonTokenType.Undefined: + writer.WriteUndefined(); + break; + case JsonTokenType.Date: + writer.WriteValue(Convert.ToDateTime(_value)); + break; + default: + throw new ArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type."); + } + } + } +} diff --git a/Src/Newtonsoft.Json/Linq/JsonTokenType.cs b/Src/Newtonsoft.Json/Linq/JsonTokenType.cs new file mode 100644 index 00000000..332b711b --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JsonTokenType.cs @@ -0,0 +1,48 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json.Linq +{ + public enum JsonTokenType + { + Object, + Array, + Constructor, + Property, + Comment, + Integer, + Float, + String, + Boolean, + Null, + Undefined, + Date + } +} diff --git a/Src/Newtonsoft.Json/MemberMapping.cs b/Src/Newtonsoft.Json/MemberMapping.cs index 910f429d..50ae699c 100644 --- a/Src/Newtonsoft.Json/MemberMapping.cs +++ b/Src/Newtonsoft.Json/MemberMapping.cs @@ -1,3 +1,28 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + using System; using System.Collections.Generic; using System.Text; diff --git a/Src/Newtonsoft.Json/MemberMappingCollection.cs b/Src/Newtonsoft.Json/MemberMappingCollection.cs index bb002862..66253f43 100644 --- a/Src/Newtonsoft.Json/MemberMappingCollection.cs +++ b/Src/Newtonsoft.Json/MemberMappingCollection.cs @@ -1,3 +1,28 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + using System; using System.Collections.Generic; using System.Text; diff --git a/Src/Newtonsoft.Json/MissingMemberHandling.cs b/Src/Newtonsoft.Json/MissingMemberHandling.cs new file mode 100644 index 00000000..90c2eafb --- /dev/null +++ b/Src/Newtonsoft.Json/MissingMemberHandling.cs @@ -0,0 +1,43 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + public enum MissingMemberHandling + { + /// + /// Throw a when a missing member is encountered during deserialization. + /// + Error = 0, + /// + /// Ignore a missing member and do not attempt to deserialize it. + /// + Ignore = 1 + } +} diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index f5335ba0..51fb3641 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -1,8 +1,8 @@ - + Debug AnyCPU - 8.0.50727 + 9.0.21022 2.0 {A9AE40FF-1A21-414A-9FE7-3BE13644CC6D} Library @@ -20,6 +20,27 @@ + + + 2.0 + + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + v3.5 true @@ -29,7 +50,8 @@ DEBUG;TRACE prompt 4 - bin\Debug\Newtonsoft.Json.XML + + pdbonly @@ -42,6 +64,9 @@ + + 3.5 + @@ -66,8 +91,20 @@ + + + + + + + + + + + + @@ -80,5 +117,22 @@ + + + False + .NET Framework 2.0 %28x86%29 + true + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + false + + \ No newline at end of file diff --git a/Src/Newtonsoft.Json/NullValueHandling.cs b/Src/Newtonsoft.Json/NullValueHandling.cs new file mode 100644 index 00000000..86373ca7 --- /dev/null +++ b/Src/Newtonsoft.Json/NullValueHandling.cs @@ -0,0 +1,47 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies null value handling options for the . + /// + public enum NullValueHandling + { + /// + /// Include null values when serializing and deserializing objects. + /// + Include = 0, + /// + /// Ignore null values when serializing and deserializing objects. + /// + Ignore = 1 + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index daff630c..02723cb5 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -54,5 +54,5 @@ using System.Security; // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.3.0.0")] -[assembly: AssemblyFileVersion("1.3.0.0")] \ No newline at end of file +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] \ No newline at end of file diff --git a/Src/Newtonsoft.Json/ReferenceLoopHandling.cs b/Src/Newtonsoft.Json/ReferenceLoopHandling.cs new file mode 100644 index 00000000..19395f36 --- /dev/null +++ b/Src/Newtonsoft.Json/ReferenceLoopHandling.cs @@ -0,0 +1,50 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies reference loop handling options for the . + /// + public enum ReferenceLoopHandling + { + /// + /// Throw a when a loop is encountered. + /// + Error = 0, + /// + /// Ignore loop references and do not serialize. + /// + Ignore = 1, + /// + /// Serialize loop references. + /// + Serialize = 2 + } +} diff --git a/Src/Newtonsoft.Json/StringBuffer.cs b/Src/Newtonsoft.Json/StringBuffer.cs index 0365799d..083a5e9a 100644 --- a/Src/Newtonsoft.Json/StringBuffer.cs +++ b/Src/Newtonsoft.Json/StringBuffer.cs @@ -84,7 +84,13 @@ namespace Newtonsoft.Json public override string ToString() { - return new string(_buffer, 0, _position); + return ToString(0, _position); + } + + public string ToString(int start, int length) + { + // TODO: validation + return new string(_buffer, start, length); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index 6616a3df..8c1d4a3a 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -29,11 +29,19 @@ using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Collections; +using System.Linq; namespace Newtonsoft.Json.Utilities { internal static class CollectionUtils { + public static IEnumerable CastValid(this IEnumerable enumerable) + { + ValidationUtils.ArgumentNotNull(enumerable, "enumerable"); + + return enumerable.Cast().Where(o => o is T).Cast(); + } + public static List CreateList(params T[] values) { return new List(values); diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index 75561e56..c6084c3a 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -209,28 +209,52 @@ namespace Newtonsoft.Json.Utilities } } - public static Type GetDictionaryValueType(Type type) + private static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { - ValidationUtils.ArgumentNotNull(type, "type"); + ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; - if (IsSubClass(type, typeof(IDictionary<,>), out genericDictionaryType)) + if (IsSubClass(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition) - throw new Exception(string.Format("Type {0} is not a dictionary.", type)); + throw new Exception(string.Format("Type {0} is not a dictionary.", dictionaryType)); - return genericDictionaryType.GetGenericArguments()[1]; + Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); + + keyType = dictionaryGenericArguments[0]; + valueType = dictionaryGenericArguments[1]; + return; } - else if (typeof(IDictionary).IsAssignableFrom(type)) + else if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { - return null; + keyType = null; + valueType = null; + return; } else { - throw new Exception(string.Format("Type {0} is not a dictionary.", type)); + throw new Exception(string.Format("Type {0} is not a dictionary.", dictionaryType)); } } + public static Type GetDictionaryValueType(Type dictionaryType) + { + Type keyType; + Type valueType; + GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); + + return valueType; + } + + public static Type GetDictionaryKeyType(Type dictionaryType) + { + Type keyType; + Type valueType; + GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); + + return keyType; + } + /// /// Tests whether the list's items are their unitialized value. ///