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.
This commit is contained in:
JamesNK
2008-02-10 10:56:19 +00:00
parent 487dc81251
commit c1ce4c366f
30 changed files with 2626 additions and 152 deletions
+174 -24
View File
@@ -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<Product>
{
}
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<int> r1 = new ReadOnlyCollection<int>(new int[] {0, 1, 2, 3, 4});
ReadOnlyCollection<int> r1 = new ReadOnlyCollection<int>(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<string>));
List<string> dataContractResult = (List<string>)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
List<string> jsonNetResult = JavaScriptConvert.DeserializeObject<List<string>>(json);
Assert.AreEqual(1, jsonNetResult.Count);
Assert.AreEqual(dataContractResult[0], jsonNetResult[0]);
}
[Test]
public void NonStringKeyDictionary()
{
Dictionary<int, int> values = new Dictionary<int, int>();
values.Add(-5, 6);
values.Add(int.MinValue, int.MaxValue);
string json = JavaScriptConvert.SerializeObject(values);
Assert.AreEqual(@"{""-5"":6,""-2147483648"":2147483647}", json);
Dictionary<int, int> newValues = JavaScriptConvert.DeserializeObject<Dictionary<int, int>>(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);
}
}
}
+432
View File
@@ -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<JProperty> 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<object> 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<int> list = a.Children<int>().ToList();
List<int> expected = new List<int>() { 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<JObject> resultObjects = o.PropertyValue<JArray>("results")
.Children<JObject>().ToList();
List<string> resultUrls = o.PropertyValue<JArray>("results")
.Children<JObject>()
.PropertyValues<string>("url")
.ToList();
List<string> expectedUrls = new List<string>() { "http://www.google.com/", "http://news.google.com/", "http://groups.google.com/", "http://maps.google.com/" };
CollectionAssert.AreEqual(expectedUrls, resultUrls);
List<JToken> 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<JArray>("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<string> Categories { get; set; }
}
private List<Post> GetPosts()
{
return new List<Post>()
{
new Post()
{
Title = "LINQ to JSON beta",
Description = "Annoucing LINQ to JSON",
Link = "http://james.newtonking.com/projects/json-net.aspx",
Categories = new List<string>() { "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<string>() { "Json.NET", "CodePlex" }
}
};
}
[Test]
public void CreateJTokenTreeNested()
{
List<Post> 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<JObject>("channel")
.PropertyValue<JArray>("item")
.Children<JObject>()
select p.PropertyValue<string>("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<JObject>("channel")
.PropertyValue<JArray>("item")
.Children<JObject>()
.PropertyValues<JArray>("category")
.Children<string>()
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
}
}
}
@@ -1,8 +1,8 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{3E6E2335-B079-4B5B-A65A-9D586914BCBB}</ProjectGuid>
<OutputType>Library</OutputType>
@@ -17,6 +17,12 @@
</SccAuxPath>
<SccProvider>
</SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>2.0</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -41,7 +47,19 @@
<HintPath>..\Lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Runtime.Serialization">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.ServiceModel">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.ServiceModel.Web">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
@@ -50,6 +68,7 @@
<Compile Include="JsonReaderTest.cs" />
<Compile Include="JsonSerializerTest.cs" />
<Compile Include="JsonWriterTest.cs" />
<Compile Include="LinqToJsonTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="XmlNodeConverterTest.cs" />
</ItemGroup>
@@ -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")]
@@ -334,7 +334,7 @@ namespace Newtonsoft.Json.Tests
XmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);
string expected = @"<?xml version=""1.0"" standalone=""no""?><root><person id=""1""><Float>2.5</Float><Integer>99</Integer></person><person id=""2""><Boolean>true</Boolean><date>2000-03-30T00:00:00.0000000+12:00</date></person></root>";
string expected = @"<?xml version=""1.0"" standalone=""no""?><root><person id=""1""><Float>2.5</Float><Integer>99</Integer></person><person id=""2""><Boolean>true</Boolean><date>2000-03-30T00:00:00.0000000+13:00</date></person></root>";
Assert.AreEqual(expected, newDoc.InnerXml);
}
+4 -16
View File
@@ -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
@@ -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;
+103 -47
View File
@@ -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<object> parameters = new List<object>();
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<object> parameters = new List<object>();
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:
+76 -28
View File
@@ -35,25 +35,6 @@ using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies reference loop handling options for the <see cref="JsonWriter"/>.
/// </summary>
public enum ReferenceLoopHandling
{
/// <summary>
/// Throw a <see cref="JsonSerializationException"/> when a loop is encountered.
/// </summary>
Error = 0,
/// <summary>
/// Ignore loop references and do not serialize.
/// </summary>
Ignore = 1,
/// <summary>
/// Serialize loop references.
/// </summary>
Serialize = 2
}
/// <summary>
/// Serializes and deserializes objects into and from the Json format.
/// The <see cref="JsonSerializer"/> 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<Type, MemberMappingCollection> _typeMemberMappings;
@@ -74,13 +57,42 @@ namespace Newtonsoft.Json
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
{
throw new ArgumentOutOfRangeException("value");
}
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members are handled during deserialization.
/// </summary>
public MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Error || value > MissingMemberHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled.
/// </summary>
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)
+6 -2
View File
@@ -49,6 +49,10 @@ namespace Newtonsoft.Json
/// <summary>
/// An object property name.
/// </summary>
StartConstructor,
/// <summary>
/// A constructor end token.
/// </summary>
PropertyName,
/// <summary>
/// A comment.
@@ -87,9 +91,9 @@ namespace Newtonsoft.Json
/// </summary>
EndArray,
/// <summary>
/// A JavaScript object constructor.
/// A constructor start token.
/// </summary>
Constructor,
EndConstructor,
/// <summary>
/// A Date.
/// </summary>
+49 -13
View File
@@ -36,6 +36,7 @@ namespace Newtonsoft.Json
{
Object,
Array,
Constructor,
None
}
@@ -63,6 +64,10 @@ namespace Newtonsoft.Json
/// </summary>
Array,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
/// <summary>
/// A property is being written.
/// </summary>
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);
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
@@ -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();
}
}
}
}
+143
View File
@@ -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<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(j => j.Ancestors());
}
//TODO
//public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(j => j.AncestorsAndSelf());
//}
public static IEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(j => j.Descendants());
}
//TODO
//public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer
//{
// ValidationUtils.ArgumentNotNull(source, "source");
// return source.SelectMany(j => j.DescendantsAndSelf());
//}
public static IEnumerable<JProperty> Properties(this IEnumerable<JObject> source)
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(d => d.Properties());
}
public static IEnumerable<T> PropertyValues<T>(this IEnumerable<JObject> 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<JToken, T>();
}
//TODO
//public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : JObject;
public static IEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JContainer
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(c => c.Children());
}
public static IEnumerable<U> Children<U>(this IEnumerable<JArray> source)
{
ValidationUtils.ArgumentNotNull(source, "source");
return source.SelectMany(c => c.Children()).Convert<JToken, U>();
}
internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, "source");
bool cast = typeof(JToken).IsAssignableFrom(typeof(U));
foreach (JToken token in source)
{
yield return Convert<JToken, U>(token, cast);
}
}
internal static U Convert<T, U>(this T token) where T : JToken
{
bool cast = typeof(JToken).IsAssignableFrom(typeof(U));
return Convert<T, U>(token, cast);
}
internal static U Convert<T, U>(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<T>(this IEnumerable<T> source) where T : JContainer;
}
}
+106
View File
@@ -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();
}
}
}
+92
View File
@@ -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();
}
}
}
+290
View File
@@ -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<JToken> Children()
{
JToken first = First;
JToken current = first;
if (current == null)
yield break;
do
{
yield return current;
} while ((current = current.Next) != first);
}
public IEnumerable<T> Children<T>()
{
return Children().Convert<JToken, T>();
}
public IEnumerable<JToken> 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());
}
}
}
+133
View File
@@ -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<JProperty> Properties()
{
return Children().Cast<JProperty>();
}
public JProperty Property(string name)
{
return Properties()
.Where(p => string.Compare(p.Name, name, StringComparison.Ordinal) == 0)
.SingleOrDefault();
}
public IEnumerable<JToken> PropertyValues()
{
return Properties().Select(p => p.Value);
}
public T PropertyValue<T>(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<JToken, T>(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();
}
}
}
+86
View File
@@ -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);
}
}
}
+415
View File
@@ -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<JToken> Ancestors()
{
for (JToken parent = Parent; parent != null; parent = parent.Parent)
{
yield return parent;
}
}
public IEnumerable<JToken> AfterSelf()
{
if (Parent == null)
yield break;
for (JToken o = Next; o != null; o = o.Next)
yield return o;
}
public IEnumerable<JToken> BeforeSelf()
{
for (JToken o = Parent.First; o != this; o = o.Next)
yield return o;
}
//public IEnumerable<JObject> ObjectsAfterSelf()
//{
// return null;
//}
//public IEnumerable<JObject> 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
}
}
+149
View File
@@ -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.");
}
}
}
}
+48
View File
@@ -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
}
}
+25
View File
@@ -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;
@@ -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;
@@ -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
{
/// <summary>
/// Throw a <see cref="JsonSerializationException"/> when a missing member is encountered during deserialization.
/// </summary>
Error = 0,
/// <summary>
/// Ignore a missing member and do not attempt to deserialize it.
/// </summary>
Ignore = 1
}
}
+57 -3
View File
@@ -1,8 +1,8 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}</ProjectGuid>
<OutputType>Library</OutputType>
@@ -20,6 +20,27 @@
</SccAuxPath>
<SccProvider>
</SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>2.0</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -29,7 +50,8 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Debug\Newtonsoft.Json.XML</DocumentationFile>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -42,6 +64,9 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
@@ -66,8 +91,20 @@
<Compile Include="JavaScriptConvert.cs" />
<Compile Include="JsonSerializationException.cs" />
<Compile Include="JsonSerializer.cs" />
<Compile Include="Linq\Extensions.cs" />
<Compile Include="Linq\JConstructor.cs" />
<Compile Include="Linq\JContainer.cs" />
<Compile Include="Linq\JObject.cs" />
<Compile Include="Linq\JArray.cs" />
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JProperty.cs" />
<Compile Include="Linq\JsonTokenType.cs" />
<Compile Include="Linq\JValue.cs" />
<Compile Include="MemberMapping.cs" />
<Compile Include="MemberMappingCollection.cs" />
<Compile Include="MissingMemberHandling.cs" />
<Compile Include="NullValueHandling.cs" />
<Compile Include="ReferenceLoopHandling.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="JsonToken.cs" />
<Compile Include="JsonWriter.cs" />
@@ -80,5 +117,22 @@
<Compile Include="Utilities\StringUtils.cs" />
<Compile Include="Utilities\ValidationUtils.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.2.0">
<Visible>False</Visible>
<ProductName>.NET Framework 2.0 %28x86%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.0">
<Visible>False</Visible>
<ProductName>.NET Framework 3.0 %28x86%29</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
+47
View File
@@ -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
{
/// <summary>
/// Specifies null value handling options for the <see cref="JsonWriter"/>.
/// </summary>
public enum NullValueHandling
{
/// <summary>
/// Include null values when serializing and deserializing objects.
/// </summary>
Include = 0,
/// <summary>
/// Ignore null values when serializing and deserializing objects.
/// </summary>
Ignore = 1
}
}
@@ -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")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
@@ -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
{
/// <summary>
/// Specifies reference loop handling options for the <see cref="JsonWriter"/>.
/// </summary>
public enum ReferenceLoopHandling
{
/// <summary>
/// Throw a <see cref="JsonSerializationException"/> when a loop is encountered.
/// </summary>
Error = 0,
/// <summary>
/// Ignore loop references and do not serialize.
/// </summary>
Ignore = 1,
/// <summary>
/// Serialize loop references.
/// </summary>
Serialize = 2
}
}
+7 -1
View File
@@ -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);
}
}
}
@@ -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<T> CastValid<T>(this IEnumerable enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
return enumerable.Cast<object>().Where(o => o is T).Cast<T>();
}
public static List<T> CreateList<T>(params T[] values)
{
return new List<T>(values);
@@ -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;
}
/// <summary>
/// Tests whether the list's items are their unitialized value.
/// </summary>