This commit is contained in:
unknown
2014-06-26 16:13:44 +12:00
80 changed files with 1483 additions and 25288 deletions
+3 -2
View File
@@ -1,6 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
ProjectSection(SolutionItems) = preProject
Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
+3 -2
View File
@@ -1,6 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Net35", "Newtonsoft.Json\Newtonsoft.Json.Net35.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Net35", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Net35.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
+2 -1
View File
@@ -1,6 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
ProjectSection(SolutionItems) = preProject
Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
@@ -150,8 +150,8 @@ namespace Newtonsoft.Json.Tests.Bson
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
CollectionAssert.AreEqual(g.ToByteArray(), (byte[])reader.Value);
Assert.AreEqual(typeof(byte[]), reader.ValueType);
Assert.AreEqual(g, reader.Value);
Assert.AreEqual(typeof(Guid), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
@@ -1603,5 +1603,80 @@ namespace Newtonsoft.Json.Tests.Bson
#endif
Assert.IsTrue(binder.BindToTypeCalled);
}
[Test]
public void GuidsShouldBeProperlyDeserialised()
{
Guid g = new Guid("822C0CE6-CC42-4753-A3C3-26F0684A4B88");
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("TheGuid");
writer.WriteValue(g);
writer.WriteEndObject();
writer.Flush();
byte[] bytes = ms.ToArray();
BsonReader reader = new BsonReader(new MemoryStream(bytes));
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
Assert.AreEqual(typeof(Guid), reader.ValueType);
Assert.AreEqual(g, (Guid)reader.Value);
Assert.IsTrue(reader.Read());
Assert.IsFalse(reader.Read());
JsonSerializer serializer = new JsonSerializer();
ObjectTestClass b = serializer.Deserialize<ObjectTestClass>(new BsonReader(new MemoryStream(bytes)));
Assert.AreEqual(typeof(Guid), b.TheGuid.GetType());
Assert.AreEqual(g, (Guid)b.TheGuid);
}
[Test]
public void GuidsShouldBeProperlyDeserialised_AsBytes()
{
Guid g = new Guid("822C0CE6-CC42-4753-A3C3-26F0684A4B88");
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("TheGuid");
writer.WriteValue(g);
writer.WriteEndObject();
writer.Flush();
byte[] bytes = ms.ToArray();
BsonReader reader = new BsonReader(new MemoryStream(bytes));
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
CollectionAssert.AreEquivalent(g.ToByteArray(), reader.ReadAsBytes());
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
Assert.AreEqual(typeof(byte[]), reader.ValueType);
CollectionAssert.AreEquivalent(g.ToByteArray(), (byte[])reader.Value);
Assert.IsTrue(reader.Read());
Assert.IsFalse(reader.Read());
JsonSerializer serializer = new JsonSerializer();
BytesTestClass b = serializer.Deserialize<BytesTestClass>(new BsonReader(new MemoryStream(bytes)));
CollectionAssert.AreEquivalent(g.ToByteArray(), b.TheGuid);
}
public class BytesTestClass
{
public byte[] TheGuid { get; set; }
}
public class ObjectTestClass
{
public object TheGuid { get; set; }
}
}
}
@@ -23,7 +23,10 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.IO;
using System.Text;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
using System;
using System.Collections.Generic;
@@ -57,7 +60,8 @@ namespace Newtonsoft.Json.Tests.Converters
],
""ArrayCol"": [
0
]
],
""DateCol"": ""2000-12-29T00:00:00Z""
},
{
""id"": 1,
@@ -69,7 +73,8 @@ namespace Newtonsoft.Json.Tests.Converters
],
""ArrayCol"": [
1
]
],
""DateCol"": ""2000-12-29T00:00:00Z""
}
]";
@@ -77,7 +82,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.IsNotNull(deserializedDataTable);
Assert.AreEqual(string.Empty, deserializedDataTable.TableName);
Assert.AreEqual(4, deserializedDataTable.Columns.Count);
Assert.AreEqual(5, deserializedDataTable.Columns.Count);
Assert.AreEqual("id", deserializedDataTable.Columns[0].ColumnName);
Assert.AreEqual(typeof(long), deserializedDataTable.Columns[0].DataType);
Assert.AreEqual("item", deserializedDataTable.Columns[1].ColumnName);
@@ -86,6 +91,8 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(typeof(DataTable), deserializedDataTable.Columns[2].DataType);
Assert.AreEqual("ArrayCol", deserializedDataTable.Columns[3].ColumnName);
Assert.AreEqual(typeof(long[]), deserializedDataTable.Columns[3].DataType);
Assert.AreEqual("DateCol", deserializedDataTable.Columns[4].ColumnName);
Assert.AreEqual(typeof(DateTime), deserializedDataTable.Columns[4].DataType);
Assert.AreEqual(2, deserializedDataTable.Rows.Count);
@@ -94,14 +101,57 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("item 0", dr1["item"]);
Assert.AreEqual("0!", ((DataTable)dr1["DataTableCol"]).Rows[0]["NestedStringCol"]);
Assert.AreEqual(0, ((long[])dr1["ArrayCol"])[0]);
Assert.AreEqual(new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc), dr1["DateCol"]);
DataRow dr2 = deserializedDataTable.Rows[1];
Assert.AreEqual(1, dr2["id"]);
Assert.AreEqual("item 1", dr2["item"]);
Assert.AreEqual("1!", ((DataTable)dr2["DataTableCol"]).Rows[0]["NestedStringCol"]);
Assert.AreEqual(1, ((long[])dr2["ArrayCol"])[0]);
Assert.AreEqual(new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc), dr2["DateCol"]);
}
#if !NET20
[Test]
public void DeserializeParseHandling()
{
string json = @"[
{
""DateCol"": ""2000-12-29T00:00:00Z"",
""FloatCol"": 99.9999999999999999999
},
{
""DateCol"": ""2000-12-29T00:00:00Z"",
""FloatCol"": 99.9999999999999999999
}
]";
DataTable deserializedDataTable = JsonConvert.DeserializeObject<DataTable>(json, new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.DateTimeOffset,
FloatParseHandling = FloatParseHandling.Decimal
});
Assert.IsNotNull(deserializedDataTable);
Assert.AreEqual(string.Empty, deserializedDataTable.TableName);
Assert.AreEqual(2, deserializedDataTable.Columns.Count);
Assert.AreEqual("DateCol", deserializedDataTable.Columns[0].ColumnName);
Assert.AreEqual(typeof(DateTimeOffset), deserializedDataTable.Columns[0].DataType);
Assert.AreEqual("FloatCol", deserializedDataTable.Columns[1].ColumnName);
Assert.AreEqual(typeof(decimal), deserializedDataTable.Columns[1].DataType);
Assert.AreEqual(2, deserializedDataTable.Rows.Count);
DataRow dr1 = deserializedDataTable.Rows[0];
Assert.AreEqual(new DateTimeOffset(2000, 12, 29, 0, 0, 0, TimeSpan.Zero), dr1["DateCol"]);
Assert.AreEqual(99.9999999999999999999m, dr1["FloatCol"]);
DataRow dr2 = deserializedDataTable.Rows[1];
Assert.AreEqual(new DateTimeOffset(2000, 12, 29, 0, 0, 0, TimeSpan.Zero), dr2["DateCol"]);
Assert.AreEqual(99.9999999999999999999m, dr2["FloatCol"]);
}
#endif
[Test]
public void Serialize()
{
@@ -225,6 +275,47 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(t1.TableName, t2.TableName);
}
[Test]
public void RoundtripBsonBytes()
{
Guid g = new Guid("EDE9A599-A7D9-44A9-9243-7C287049DD20");
var table = new DataTable();
table.Columns.Add("data", typeof(byte[]));
table.Columns.Add("id", typeof(Guid));
table.Rows.Add(Encoding.UTF8.GetBytes("Hello world!"), g);
JsonSerializer serializer = new JsonSerializer();
MemoryStream ms = new MemoryStream();
BsonWriter bw = new BsonWriter(ms);
serializer.Serialize(bw, table);
JToken o = JToken.ReadFrom(new BsonReader(new MemoryStream(ms.ToArray())) { ReadRootValueAsArray = true });
Assert.AreEqual(@"[
{
""data"": ""SGVsbG8gd29ybGQh"",
""id"": ""ede9a599-a7d9-44a9-9243-7c287049dd20""
}
]", o.ToString());
DataTable deserializedDataTable = serializer.Deserialize<DataTable>(new BsonReader(new MemoryStream(ms.ToArray())) { ReadRootValueAsArray = true });
Assert.AreEqual(string.Empty, deserializedDataTable.TableName);
Assert.AreEqual(2, deserializedDataTable.Columns.Count);
Assert.AreEqual("data", deserializedDataTable.Columns[0].ColumnName);
Assert.AreEqual(typeof(byte[]), deserializedDataTable.Columns[0].DataType);
Assert.AreEqual("id", deserializedDataTable.Columns[1].ColumnName);
Assert.AreEqual(typeof(Guid), deserializedDataTable.Columns[1].DataType);
Assert.AreEqual(1, deserializedDataTable.Rows.Count);
DataRow dr1 = deserializedDataTable.Rows[0];
CollectionAssert.AreEquivalent(Encoding.UTF8.GetBytes("Hello world!"), (byte[])dr1["data"]);
Assert.AreEqual(g, (Guid)dr1["id"]);
}
[Test]
public void SerializeDataTableWithNull()
{
@@ -406,7 +406,7 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void XmlDocumentTypeSerialize()
{
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?><!DOCTYPE STOCKQUOTE PUBLIC ""-//W3C//DTD StockQuote 1.5//EN"" ""http://www.irxml.org/dtd/stockquote_1.5.dtd""><STOCKQUOTE ROWCOUNT=""2""><RESULT><ROW><ASK>0</ASK><BID>0</BID><CHANGE>-16.310</CHANGE><COMPANYNAME>Dow Jones</COMPANYNAME><DATETIME>2014-04-17 15:50:37</DATETIME><DIVIDEND>0</DIVIDEND><EPS>0</EPS><EXCHANGE></EXCHANGE><HIGH>16460.490</HIGH><LASTDATETIME>2014-04-17 15:50:37</LASTDATETIME><LASTPRICE>16408.540</LASTPRICE><LOW>16368.140</LOW><OPEN>16424.140</OPEN><PCHANGE>-0.099</PCHANGE><PE>0</PE><PREVIOUSCLOSE>16424.850</PREVIOUSCLOSE><SHARES>0</SHARES><TICKER>DJII</TICKER><TRADES>0</TRADES><VOLUME>136188700</VOLUME><YEARHIGH>11309.000</YEARHIGH><YEARLOW>9302.280</YEARLOW><YIELD>0</YIELD></ROW><ROW><ASK>0</ASK><BID>0</BID><CHANGE>9.290</CHANGE><COMPANYNAME>NASDAQ</COMPANYNAME><DATETIME>2014-04-17 15:40:01</DATETIME><DIVIDEND>0</DIVIDEND><EPS>0</EPS><EXCHANGE></EXCHANGE><HIGH>4110.460</HIGH><LASTDATETIME>2014-04-17 15:40:01</LASTDATETIME><LASTPRICE>4095.520</LASTPRICE><LOW>4064.700</LOW><OPEN>4080.300</OPEN><PCHANGE>0.227</PCHANGE><PE>0</PE><PREVIOUSCLOSE>4086.230</PREVIOUSCLOSE><SHARES>0</SHARES><TICKER>COMP</TICKER><TRADES>0</TRADES><VOLUME>1784210100</VOLUME><YEARHIGH>4371.710</YEARHIGH><YEARLOW>3154.960</YEARLOW><YIELD>0</YIELD></ROW></RESULT><STATUS>Couldn't find ticker: SPIC?</STATUS><STATUSCODE>2</STATUSCODE></STOCKQUOTE>";
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?><!DOCTYPE STOCKQUOTE PUBLIC ""-//W3C//DTD StockQuote 1.5//EN"" ""http://www.idontexistnopenopewhatnope123.org/dtd/stockquote_1.5.dtd""><STOCKQUOTE ROWCOUNT=""2""><RESULT><ROW><ASK>0</ASK><BID>0</BID><CHANGE>-16.310</CHANGE><COMPANYNAME>Dow Jones</COMPANYNAME><DATETIME>2014-04-17 15:50:37</DATETIME><DIVIDEND>0</DIVIDEND><EPS>0</EPS><EXCHANGE></EXCHANGE><HIGH>16460.490</HIGH><LASTDATETIME>2014-04-17 15:50:37</LASTDATETIME><LASTPRICE>16408.540</LASTPRICE><LOW>16368.140</LOW><OPEN>16424.140</OPEN><PCHANGE>-0.099</PCHANGE><PE>0</PE><PREVIOUSCLOSE>16424.850</PREVIOUSCLOSE><SHARES>0</SHARES><TICKER>DJII</TICKER><TRADES>0</TRADES><VOLUME>136188700</VOLUME><YEARHIGH>11309.000</YEARHIGH><YEARLOW>9302.280</YEARLOW><YIELD>0</YIELD></ROW><ROW><ASK>0</ASK><BID>0</BID><CHANGE>9.290</CHANGE><COMPANYNAME>NASDAQ</COMPANYNAME><DATETIME>2014-04-17 15:40:01</DATETIME><DIVIDEND>0</DIVIDEND><EPS>0</EPS><EXCHANGE></EXCHANGE><HIGH>4110.460</HIGH><LASTDATETIME>2014-04-17 15:40:01</LASTDATETIME><LASTPRICE>4095.520</LASTPRICE><LOW>4064.700</LOW><OPEN>4080.300</OPEN><PCHANGE>0.227</PCHANGE><PE>0</PE><PREVIOUSCLOSE>4086.230</PREVIOUSCLOSE><SHARES>0</SHARES><TICKER>COMP</TICKER><TRADES>0</TRADES><VOLUME>1784210100</VOLUME><YEARHIGH>4371.710</YEARHIGH><YEARLOW>3154.960</YEARLOW><YIELD>0</YIELD></ROW></RESULT><STATUS>Couldn't find ticker: SPIC?</STATUS><STATUSCODE>2</STATUSCODE></STOCKQUOTE>";
string expected = @"{
""?xml"": {
@@ -416,7 +416,7 @@ namespace Newtonsoft.Json.Tests.Converters
""!DOCTYPE"": {
""@name"": ""STOCKQUOTE"",
""@public"": ""-//W3C//DTD StockQuote 1.5//EN"",
""@system"": ""http://www.irxml.org/dtd/stockquote_1.5.dtd""
""@system"": ""http://www.idontexistnopenopewhatnope123.org/dtd/stockquote_1.5.dtd""
},
""STOCKQUOTE"": {
""@ROWCOUNT"": ""2"",
@@ -480,6 +480,7 @@ namespace Newtonsoft.Json.Tests.Converters
}";
XmlDocument doc1 = new XmlDocument();
doc1.XmlResolver = null;
doc1.LoadXml(xml);
string json1 = JsonConvert.SerializeXmlNode(doc1, Formatting.Indented);
+171
View File
@@ -0,0 +1,171 @@
#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.Threading.Tasks;
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class DemoTests : TestFixtureBase
{
public class HtmlColor
{
public int Red { get; set; }
public int Green { get; set; }
public int Blue { get; set; }
}
[Test]
public void JsonConverter()
{
HtmlColor red = new HtmlColor
{
Red = 255,
Green = 0,
Blue = 0
};
string json = JsonConvert.SerializeObject(red, new JsonSerializerSettings
{
Formatting = Formatting.Indented
});
// {
// "Red": 255,
// "Green": 0,
// "Blue": 0
// }
json = JsonConvert.SerializeObject(red, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = { new HtmlColorConverter() }
});
// "#FF0000"
HtmlColor r2 = JsonConvert.DeserializeObject<HtmlColor>(json, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = { new HtmlColorConverter() }
});
Assert.AreEqual(255, r2.Red);
Assert.AreEqual(0, r2.Green);
Assert.AreEqual(0, r2.Blue);
Console.WriteLine(json);
}
public class PersonDemo
{
public string Name { get; set; }
public int Age { get; set; }
public string Job { get; set; }
}
public class Session
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
[Test]
public void GenerateSchema()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Session));
// {
// "type": "object",
// "properties": {
// "Name": {
// "required": true,
// "type": [
// "string",
// "null"
// ]
// },
// "Date": {
// "required": true,
// "type": "string"
// }
// }
// }
}
public class HtmlColorConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// create hex string from value
HtmlColor color = (HtmlColor)value;
string hexString = color.Red.ToString("X2")
+ color.Green.ToString("X2")
+ color.Blue.ToString("X2");
// write value to json
writer.WriteValue("#" + hexString);
}
//public override object ReadJson(JsonReader reader, Type objectType,
// object existingValue, JsonSerializer serializer)
//{
// throw new NotImplementedException();
//}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
// get hex string
string hexString = (string)reader.Value;
hexString = hexString.TrimStart('#');
// build html color from hex
return new HtmlColor
{
Red = Convert.ToInt32(hexString.Substring(0, 2), 16),
Green = Convert.ToInt32(hexString.Substring(2, 2), 16),
Blue = Convert.ToInt32(hexString.Substring(4, 2), 16)
};
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(HtmlColor);
}
}
}
}
@@ -57,24 +57,24 @@ namespace Newtonsoft.Json.Tests.Documentation
{
#region IsValidBasic
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties':
{
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
'description': 'A person',
'type': 'object',
'properties':
{
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true
@@ -45,9 +45,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
// }
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
@@ -26,6 +26,9 @@
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35)
@@ -995,6 +998,45 @@ now brown cow?", '"', true);
Assert.AreEqual("Bad Boys", m.Name);
}
#if !NET20
[Test]
public void TestJsonDateTimeOffsetRoundtrip()
{
var now = DateTimeOffset.Now;
var dict = new Dictionary<string, object> { { "foo", now } };
var settings = new JsonSerializerSettings();
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
settings.DateParseHandling = DateParseHandling.DateTimeOffset;
settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
var json = JsonConvert.SerializeObject(dict, settings);
var newDict = new Dictionary<string, object>();
JsonConvert.PopulateObject(json, newDict, settings);
var date = newDict["foo"];
Assert.AreEqual(date, now);
}
#endif
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
[Test]
public void IntegerLengthOverflows()
{
// Maximum javascript number length (in characters) is 380
JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}");
JValue v = (JValue)o["biginteger"];
Assert.AreEqual(JTokenType.Integer, v.Type);
Assert.AreEqual(typeof(BigInteger), v.Value.GetType());
Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value);
ExceptionAssert.Throws<JsonReaderException>(
"JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395.",
() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"));
}
#endif
//[Test]
public void StackOverflowTest()
{
@@ -47,6 +47,27 @@ namespace Newtonsoft.Json.Tests
[TestFixture]
public class JsonTextReaderTest : TestFixtureBase
{
[Test]
public void ReadInvalidNonBase10Number()
{
string json = "0aq2dun13.hod";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>("Input string '0a' is not a valid number. Path '', line 1, position 2.",
() => { reader.Read(); });
reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>("Input string '0a' is not a valid decimal. Path '', line 1, position 2.",
() => { reader.ReadAsDecimal(); });
reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>("Input string '0a' is not a valid integer. Path '', line 1, position 2.",
() => { reader.ReadAsInt32(); });
}
[Test]
public void ThrowErrorWhenParsingUnquoteStringThatStartsWithNE()
{
@@ -75,6 +75,7 @@
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Converters\VersionConverterTests.cs" />
<Compile Include="Converters\XmlNodeConverterTest.cs" />
<Compile Include="DemoTests.cs" />
<Compile Include="Documentation\ConditionalPropertiesTests.cs" />
<Compile Include="Documentation\ConvertingJsonAndXmlTests.cs" />
<Compile Include="Documentation\JsonNetVsWindowsDataJsonTests.cs" />
@@ -75,4 +75,4 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.3.17312")]
[assembly: AssemblyFileVersion("6.0.3.17421")]
@@ -108,6 +108,35 @@ namespace Newtonsoft.Json.Tests.Serialization
[TestFixture]
public class ContractResolverTests : TestFixtureBase
{
[Test]
public void JsonPropertyDefaultValue()
{
JsonProperty p = new JsonProperty();
Assert.AreEqual(null, p.GetResolvedDefaultValue());
Assert.AreEqual(null, p.DefaultValue);
p.PropertyType = typeof(int);
Assert.AreEqual(0 , p.GetResolvedDefaultValue());
Assert.AreEqual(null, p.DefaultValue);
p.PropertyType = typeof(DateTime);
Assert.AreEqual(new DateTime(), p.GetResolvedDefaultValue());
Assert.AreEqual(null, p.DefaultValue);
p.PropertyType = null;
Assert.AreEqual(null, p.GetResolvedDefaultValue());
Assert.AreEqual(null, p.DefaultValue);
p.PropertyType = typeof(CompareOptions);
Assert.AreEqual(CompareOptions.None, (CompareOptions)p.GetResolvedDefaultValue());
Assert.AreEqual(null, p.DefaultValue);
}
[Test]
public void ListInterface()
{
@@ -46,6 +46,42 @@ namespace Newtonsoft.Json.Tests.Serialization
[TestFixture]
public class DefaultValueHandlingTests : TestFixtureBase
{
public class MyClass
{
[JsonIgnore]
public MyEnum Status { get; set; }
private string _data;
public string Data
{
get { return _data; }
set
{
_data = value;
if (_data != null && _data.StartsWith("Other"))
{
this.Status = MyEnum.Other;
}
}
}
}
public enum MyEnum
{
Default = 0,
Other
}
[Test]
public void PopulateWithJsonIgnoreAttribute()
{
string json = "{\"Data\":\"Other with some more text\"}";
MyClass result = JsonConvert.DeserializeObject<MyClass>(json, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate });
Assert.AreEqual(MyEnum.Other, result.Status);
}
[Test]
public void Include()
{
@@ -91,6 +91,26 @@ namespace Newtonsoft.Json.Tests.Serialization
[TestFixture]
public class JsonSerializerTest : TestFixtureBase
{
#if !NET20
[Test]
public void PopulateResetSettings()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"[""2000-01-01T01:01:01+00:00""]"));
Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
JsonSerializer serializer = new JsonSerializer();
serializer.DateParseHandling = DateParseHandling.DateTimeOffset;
IList<object> l = new List<object>();
serializer.Populate(reader, l);
Assert.AreEqual(typeof(DateTimeOffset), l[0].GetType());
Assert.AreEqual(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero), l[0]);
Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
}
#endif
public class BaseClass
{
internal bool IsTransient { get; set; }
@@ -233,6 +253,56 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(input.Result, deserialized.Result);
}
[Test]
public void DeserializeJObjectWithComments()
{
string json = @"/* Test */
{
/*Test*/""A"":/* Test */true/* Test */,
/* Test */""B"":/* Test */false/* Test */,
/* Test */""C"":/* Test */[
/* Test */
1/* Test */
]/* Test */
}
/* Test */";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
Assert.AreEqual(3, o.Count);
Assert.AreEqual(true, (bool)o["A"]);
Assert.AreEqual(false, (bool)o["B"]);
Assert.AreEqual(3, o["C"].Count());
Assert.AreEqual(JTokenType.Comment, o["C"][0].Type);
Assert.AreEqual(1, (int)o["C"][1]);
Assert.AreEqual(JTokenType.Comment, o["C"][2].Type);
Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
json = @"{/* Test */}";
o = (JObject)JsonConvert.DeserializeObject(json);
Assert.AreEqual(0, o.Count);
Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
json = @"{""A"": true/* Test */}";
o = (JObject)JsonConvert.DeserializeObject(json);
Assert.AreEqual(1, o.Count);
Assert.AreEqual(true, (bool)o["A"]);
Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
}
public class CommentTestObject
{
public bool? A { get; set; }
}
[Test]
public void DeserializeCommentTestObjectWithComments()
{
CommentTestObject o = JsonConvert.DeserializeObject<CommentTestObject>(@"{/* Test */}");
Assert.AreEqual(null, o.A);
o = JsonConvert.DeserializeObject<CommentTestObject>(@"{""A"": true/* Test */}");
Assert.AreEqual(true, o.A);
}
[Test]
public void JsonSerializerProperties()
{
@@ -2418,7 +2488,7 @@ keyword such as type of business.""
Assert.AreEqual("titleId", n.FidOrder[n.FidOrder.Count - 1]);
}
#if !(NET20 || NETFX_CORE || PORTABLE || PORTABLE40)
#if !(NET20 || NETFX_CORE)
[MetadataType(typeof(OptInClassMetadata))]
public class OptInClass
{
@@ -5736,6 +5806,88 @@ To fix this error either change the environment to be fully trusted, change the
}
}
public class ReflectionContractResolver : DefaultContractResolver
{
protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
{
return new ReflectionValueProvider(member);
}
}
[Test]
public void SerializeStaticDefault()
{
DefaultContractResolver contractResolver = new DefaultContractResolver();
StaticTestClass c = new StaticTestClass
{
x = int.MaxValue
};
StaticTestClass.y = 2;
StaticTestClass.z = 3;
string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Assert.AreEqual(@"{
""x"": 2147483647,
""y"": 2,
""z"": 3
}", json);
StaticTestClass c2 = JsonConvert.DeserializeObject<StaticTestClass>(@"{
""x"": -1,
""y"": -2,
""z"": -3
}",
new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Assert.AreEqual(-1, c2.x);
Assert.AreEqual(-2, StaticTestClass.y);
Assert.AreEqual(-3, StaticTestClass.z);
}
[Test]
public void SerializeStaticReflection()
{
ReflectionContractResolver contractResolver = new ReflectionContractResolver();
StaticTestClass c = new StaticTestClass
{
x = int.MaxValue
};
StaticTestClass.y = 2;
StaticTestClass.z = 3;
string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Assert.AreEqual(@"{
""x"": 2147483647,
""y"": 2,
""z"": 3
}", json);
StaticTestClass c2 = JsonConvert.DeserializeObject<StaticTestClass>(@"{
""x"": -1,
""y"": -2,
""z"": -3
}",
new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Assert.AreEqual(-1, c2.x);
Assert.AreEqual(-2, StaticTestClass.y);
Assert.AreEqual(-3, StaticTestClass.z);
}
#if !(NET20 || NETFX_CORE)
[Test]
public void DeserializeDecimalsWithCulture()
@@ -7857,6 +8009,76 @@ Parameter name: value",
Assert.AreEqual(dt, (DateTimeOffset)v.Value);
}
#endif
public class ErroringJsonConverter : JsonConverter
{
public ErroringJsonConverter(string s)
{
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
}
[JsonConverter(typeof(ErroringJsonConverter))]
public class ErroringTestClass
{
}
[Test]
public void ErrorCreatingJsonConverter()
{
ExceptionAssert.Throws<JsonException>(
"Error creating 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ErroringJsonConverter'.",
() => JsonConvert.SerializeObject(new ErroringTestClass()));
}
[Test]
public void DeserializeInvalidOctalRootError()
{
ExceptionAssert.Throws<JsonReaderException>(
"Input string '020474068' is not a valid number. Path '', line 1, position 9.",
() => JsonConvert.DeserializeObject<string>("020474068"));
}
[Test]
public void DeserializedDerivedWithPrivate()
{
string json = @"{
""DerivedProperty"": ""derived"",
""BaseProperty"": ""base""
}";
var d = JsonConvert.DeserializeObject<DerivedWithPrivate>(json);
Assert.AreEqual("base", d.BaseProperty);
Assert.AreEqual("derived", d.DerivedProperty);
}
}
public class DerivedWithPrivate : BaseWithPrivate
{
[JsonProperty]
public string DerivedProperty { get; private set; }
}
public class BaseWithPrivate
{
[JsonProperty]
public string BaseProperty { get; private set; }
}
public abstract class Test<T>
@@ -7986,4 +8208,22 @@ Parameter name: value",
public double Height { get; set; }
public decimal Price { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class StaticTestClass
{
[JsonProperty]
public int x = 1;
[JsonProperty]
public static int y = 2;
[JsonProperty]
public static int z { get; set; }
static StaticTestClass()
{
z = 3;
}
}
}
@@ -289,6 +289,66 @@ Newtonsoft.Json Error: 0 : Error!
Assert.IsFalse(traceWriter.TraceRecords.Any(r => r.Level == TraceLevel.Verbose));
}
[Test]
public void Populate()
{
InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
{
LevelFilter = TraceLevel.Info
};
TraceTestObject o2 = new TraceTestObject();
JsonConvert.PopulateObject(@"{
""IntList"": [
1,
2
],
""StringArray"": [
""1"",
""2""
],
""Version"": {
""Major"": 1,
""Minor"": 2,
""Build"": 3,
""Revision"": 4,
""MajorRevision"": 0,
""MinorRevision"": 4
},
""StringDictionary"": {
""1"": ""!"",
""Two"": ""!!"",
""III"": ""!!!""
}
}",
o2,
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
Assert.AreEqual(2, o2.IntList.Count);
Assert.AreEqual(2, o2.StringArray.Length);
Assert.AreEqual(1, o2.Version.Major);
Assert.AreEqual(2, o2.Version.Minor);
Assert.AreEqual(3, o2.StringDictionary.Count);
Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path 'IntList', line 2, position 13.", traceWriter.TraceRecords[0].Message);
Assert.AreEqual("Started deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList', line 2, position 15.", traceWriter.TraceRecords[1].Message);
Assert.IsTrue(traceWriter.TraceRecords[2].Message.StartsWith("Finished deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList'"));
Assert.AreEqual("Started deserializing System.String[]. Path 'StringArray', line 6, position 19.", traceWriter.TraceRecords[3].Message);
Assert.IsTrue(traceWriter.TraceRecords[4].Message.StartsWith("Finished deserializing System.String[]. Path 'StringArray'"));
Assert.AreEqual("Deserializing System.Version using creator with parameters: Major, Minor, Build, Revision. Path 'Version.Major', line 11, position 13.", traceWriter.TraceRecords[5].Message);
Assert.IsTrue(traceWriter.TraceRecords[6].Message.StartsWith("Started deserializing System.Version. Path 'Version'"));
Assert.IsTrue(traceWriter.TraceRecords[7].Message.StartsWith("Finished deserializing System.Version. Path 'Version'"));
Assert.AreEqual("Started deserializing System.Collections.Generic.IDictionary`2[System.String,System.String]. Path 'StringDictionary.1', line 19, position 9.", traceWriter.TraceRecords[8].Message);
Assert.IsTrue(traceWriter.TraceRecords[9].Message.StartsWith("Finished deserializing System.Collections.Generic.IDictionary`2[System.String,System.String]. Path 'StringDictionary'"));
Assert.IsTrue(traceWriter.TraceRecords[10].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path ''"));
Assert.IsFalse(traceWriter.TraceRecords.Any(r => r.Level == TraceLevel.Verbose));
}
[Test]
public void ErrorDeserializing()
{
+2 -1
View File
@@ -1,6 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.WinRT", "Newtonsoft.Json\Newtonsoft.Json.WinRT.csproj", "{263136A2-B89B-424E-A87A-F988CAA8D032}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.WinRT", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.WinRT.csproj", "{8D9C2E69-9FD7-4A7A-866C-739C9207CD0B}"
+2 -1
View File
@@ -1,6 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json", "Newtonsoft.Json\Newtonsoft.Json.csproj", "{EEEA67F9-9089-481D-A4DC-0966DEC9FD7D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.csproj", "{CCD1B8C4-7349-409C-A090-A9B9A1ABD981}"
+10 -3
View File
@@ -536,7 +536,14 @@ namespace Newtonsoft.Json.Bson
break;
}
case BsonType.Binary:
SetToken(JsonToken.Bytes, ReadBinary());
BsonBinaryType binaryType;
byte[] data = ReadBinary(out binaryType);
object value = (binaryType != BsonBinaryType.Uuid)
? data
: (object)new Guid(data);
SetToken(JsonToken.Bytes, value);
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
@@ -602,11 +609,11 @@ namespace Newtonsoft.Json.Bson
}
}
private byte[] ReadBinary()
private byte[] ReadBinary(out BsonBinaryType binaryType)
{
int dataLength = ReadInt32();
BsonBinaryType binaryType = (BsonBinaryType)ReadByte();
binaryType = (BsonBinaryType)ReadByte();
#pragma warning disable 612,618
// the old binary type has the data length repeated in the data for some reason
@@ -32,13 +32,6 @@ using System.Collections.Generic;
namespace Newtonsoft.Json.Converters
{
#if !NET20
internal interface IBinary
{
byte[] ToArray();
}
#endif
/// <summary>
/// Converts a binary value to and from a base 64 string value.
/// </summary>
@@ -46,6 +39,8 @@ namespace Newtonsoft.Json.Converters
{
#if !NET20
private const string BinaryTypeName = "System.Data.Linq.Binary";
private const string BinaryToArrayName = "ToArray";
private ReflectionObject _reflectionObject;
#endif
/// <summary>
@@ -72,8 +67,8 @@ namespace Newtonsoft.Json.Converters
#if !(NET20)
if (value.GetType().AssignableToTypeName(BinaryTypeName))
{
IBinary binary = DynamicWrapper.CreateWrapper<IBinary>(value);
return binary.ToArray();
EnsureReflectionObject(value.GetType());
return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName);
}
#endif
if (value is SqlBinary)
@@ -82,6 +77,14 @@ namespace Newtonsoft.Json.Converters
throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#if !NET20
private void EnsureReflectionObject(Type t)
{
if (_reflectionObject == null)
_reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);
}
#endif
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
@@ -122,10 +125,13 @@ namespace Newtonsoft.Json.Converters
throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
#if !NET20
if (t.AssignableToTypeName(BinaryTypeName))
return Activator.CreateInstance(t, data);
{
EnsureReflectionObject(t);
return _reflectionObject.Creator(data);
}
#endif
if (t == typeof(SqlBinary))
@@ -179,5 +185,4 @@ namespace Newtonsoft.Json.Converters
}
}
}
#endif
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Converters
dr[columnName] = nestedDt;
}
else if (column.DataType.IsArray)
else if (column.DataType.IsArray && column.DataType != typeof(byte[]))
{
if (reader.TokenType == JsonToken.StartArray)
reader.Read();
@@ -180,17 +180,15 @@ namespace Newtonsoft.Json.Converters
switch (tokenType)
{
case JsonToken.Integer:
return typeof(long);
case JsonToken.Boolean:
case JsonToken.Float:
return typeof(double);
case JsonToken.String:
case JsonToken.Date:
case JsonToken.Bytes:
return reader.ValueType;
case JsonToken.Null:
case JsonToken.Undefined:
return typeof(string);
case JsonToken.Boolean:
return typeof(bool);
case JsonToken.Date:
return typeof(DateTime);
case JsonToken.StartArray:
reader.Read();
if (reader.TokenType == JsonToken.StartObject)
@@ -31,12 +31,6 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
internal interface IEntityKeyMember
{
string Key { get; set; }
object Value { get; set; }
}
/// <summary>
/// Converts an Entity Framework EntityKey to and from JSON.
/// </summary>
@@ -48,6 +42,8 @@ namespace Newtonsoft.Json.Converters
private const string TypePropertyName = "Type";
private const string ValuePropertyName = "Value";
private static ReflectionObject _reflectionObject;
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
@@ -56,26 +52,30 @@ namespace Newtonsoft.Json.Converters
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
EnsureReflectionObject(value.GetType());
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;
string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName);
object keyValue = _reflectionObject.GetValue(value, ValuePropertyName);
Type keyValueType = (keyValue != null) ? keyValue.GetType() : null;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName);
writer.WriteValue(entityKeyMember.Key);
writer.WriteValue(keyName);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(TypePropertyName) : TypePropertyName);
writer.WriteValue((keyType != null) ? keyType.FullName : null);
writer.WriteValue((keyValueType != null) ? keyValueType.FullName : null);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValuePropertyName) : ValuePropertyName);
if (keyType != null)
if (keyValueType != null)
{
string valueJson;
if (JsonSerializerInternalWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out valueJson))
writer.WriteValue(valueJson);
else
writer.WriteValue(entityKeyMember.Value);
writer.WriteValue(keyValue);
}
else
{
@@ -109,11 +109,13 @@ namespace Newtonsoft.Json.Converters
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(Activator.CreateInstance(objectType));
EnsureReflectionObject(objectType);
object entityKeyMember = _reflectionObject.Creator();
ReadAndAssertProperty(reader, KeyPropertyName);
ReadAndAssert(reader);
entityKeyMember.Key = reader.Value.ToString();
_reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value.ToString());
ReadAndAssertProperty(reader, TypePropertyName);
ReadAndAssert(reader);
@@ -123,11 +125,17 @@ namespace Newtonsoft.Json.Converters
ReadAndAssertProperty(reader, ValuePropertyName);
ReadAndAssert(reader);
entityKeyMember.Value = serializer.Deserialize(reader, t);
_reflectionObject.SetValue(entityKeyMember, ValuePropertyName, serializer.Deserialize(reader, t));
ReadAndAssert(reader);
return DynamicWrapper.GetUnderlyingObject(entityKeyMember);
return entityKeyMember;
}
private static void EnsureReflectionObject(Type objectType)
{
if (_reflectionObject == null)
_reflectionObject = ReflectionObject.Create(objectType, KeyPropertyName, ValuePropertyName);
}
/// <summary>
@@ -39,6 +39,17 @@ namespace Newtonsoft.Json.Converters
private const string KeyName = "Key";
private const string ValueName = "Value";
private static readonly ThreadSafeStore<Type, ReflectionObject> ReflectionObjectPerType = new ThreadSafeStore<Type, ReflectionObject>(InitializeReflectionObject);
private static ReflectionObject InitializeReflectionObject(Type t)
{
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
return ReflectionObject.Create(t, t.GetConstructor(new[] { keyType, valueType }), KeyName, ValueName);
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
@@ -47,22 +58,15 @@ namespace Newtonsoft.Json.Converters
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Type t = value.GetType();
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
PropertyInfo keyProperty = t.GetProperty(KeyName);
PropertyInfo valueProperty = t.GetProperty(ValueName);
ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType());
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value), keyType);
serializer.Serialize(writer, reflectionObject.GetValue(value, KeyName), reflectionObject.GetType(KeyName));
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName);
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value), valueType);
serializer.Serialize(writer, reflectionObject.GetValue(value, ValueName), reflectionObject.GetType(ValueName));
writer.WriteEndObject();
}
@@ -78,6 +82,12 @@ namespace Newtonsoft.Json.Converters
{
bool isNullable = ReflectionUtils.IsNullableType(objectType);
Type t = (isNullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);
if (reader.TokenType == JsonToken.Null)
{
if (!isNullable)
@@ -86,14 +96,6 @@ namespace Newtonsoft.Json.Converters
return null;
}
Type t = (isNullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
object key = null;
object value = null;
@@ -105,12 +107,12 @@ namespace Newtonsoft.Json.Converters
if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
{
reader.Read();
key = serializer.Deserialize(reader, keyType);
key = serializer.Deserialize(reader, reflectionObject.GetType(KeyName));
}
else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
{
reader.Read();
value = serializer.Deserialize(reader, valueType);
value = serializer.Deserialize(reader, reflectionObject.GetType(ValueName));
}
else
{
@@ -120,7 +122,7 @@ namespace Newtonsoft.Json.Converters
reader.Read();
}
return Activator.CreateInstance(t, key, value);
return reflectionObject.Creator(key, value);
}
/// <summary>
@@ -1261,6 +1261,9 @@ namespace Newtonsoft.Json.Converters
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments");
XmlDocument d = new XmlDocument();
// prevent http request when resolving any DTD references
d.XmlResolver = null;
document = new XmlDocumentWrapper(d);
rootNode = document;
}
+16 -16
View File
@@ -551,7 +551,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// If this is null, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
@@ -565,7 +565,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// If this is null, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
@@ -587,7 +587,7 @@ namespace Newtonsoft.Json
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// If this is null, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
@@ -602,7 +602,7 @@ namespace Newtonsoft.Json
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// If this is null, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
@@ -670,7 +670,7 @@ namespace Newtonsoft.Json
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// If this is null, default serialization settings will be used.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
@@ -687,7 +687,7 @@ namespace Newtonsoft.Json
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
@@ -699,7 +699,7 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
@@ -712,7 +712,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
@@ -723,7 +723,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
@@ -757,7 +757,7 @@ namespace Newtonsoft.Json
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
@@ -784,7 +784,7 @@ namespace Newtonsoft.Json
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
@@ -815,7 +815,7 @@ namespace Newtonsoft.Json
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
@@ -858,7 +858,7 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
@@ -891,7 +891,7 @@ namespace Newtonsoft.Json
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
@@ -921,7 +921,7 @@ namespace Newtonsoft.Json
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
@@ -944,7 +944,7 @@ namespace Newtonsoft.Json
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>
/// A task that represents the asynchronous populate operation.
@@ -57,17 +57,5 @@ namespace Newtonsoft.Json
_converterType = converterType;
}
internal static JsonConverter CreateJsonConverterInstance(Type converterType)
{
try
{
return (JsonConverter)Activator.CreateInstance(converterType);
}
catch (Exception ex)
{
throw new JsonException("Error creating {0}".FormatWith(CultureInfo.InvariantCulture, converterType), ex);
}
}
}
}
+1 -1
View File
@@ -92,7 +92,7 @@ namespace Newtonsoft.Json
internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message)
{
// don't add a fullstop and space when message ends with a new line
if (!message.EndsWith(Environment.NewLine))
if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
{
message = message.Trim();
+10 -1
View File
@@ -513,7 +513,16 @@ namespace Newtonsoft.Json
return null;
if (t == JsonToken.Bytes)
{
if (ValueType == typeof(Guid))
{
byte[] data = ((Guid)Value).ToByteArray();
SetToken(JsonToken.Bytes, data, false);
return data;
}
return (byte[])Value;
}
if (t == JsonToken.StartArray)
{
@@ -774,7 +783,7 @@ namespace Newtonsoft.Json
if (Value.ToString() == JsonTypeReflector.TypePropertyName)
{
ReadInternal();
if (Value != null && Value.ToString().StartsWith("System.Byte[]"))
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
ReadInternal();
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
+96 -46
View File
@@ -43,7 +43,6 @@ namespace Newtonsoft.Json
/// </summary>
public class JsonSerializer
{
#region Properties_binder
internal TypeNameHandling _typeNameHandling;
internal FormatterAssemblyStyle _typeNameAssemblyFormat;
internal PreserveReferencesHandling _preserveReferencesHandling;
@@ -428,7 +427,6 @@ namespace Newtonsoft.Json
{
return (_checkAdditionalContent != null);
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
@@ -623,8 +621,26 @@ namespace Newtonsoft.Json
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(target, "target");
// set serialization options onto reader
CultureInfo previousCulture;
DateTimeZoneHandling? previousDateTimeZoneHandling;
DateParseHandling? previousDateParseHandling;
FloatParseHandling? previousFloatParseHandling;
int? previousMaxDepth;
string previousDateFormatString;
SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString);
TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
? new TraceJsonReader(reader)
: null;
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
serializerReader.Populate(reader, target);
serializerReader.Populate(traceJsonReader ?? reader, target);
if (traceJsonReader != null)
TraceWriter.Trace(TraceLevel.Verbose, "Deserialized JSON: " + Environment.NewLine + traceJsonReader.GetJson(), null);
ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
}
/// <summary>
@@ -678,47 +694,13 @@ namespace Newtonsoft.Json
ValidationUtils.ArgumentNotNull(reader, "reader");
// set serialization options onto reader
CultureInfo previousCulture = null;
if (_culture != null && !_culture.Equals(reader.Culture))
{
previousCulture = reader.Culture;
reader.Culture = _culture;
}
DateTimeZoneHandling? previousDateTimeZoneHandling = null;
if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
{
previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
reader.DateTimeZoneHandling = _dateTimeZoneHandling.Value;
}
DateParseHandling? previousDateParseHandling = null;
if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling)
{
previousDateParseHandling = reader.DateParseHandling;
reader.DateParseHandling = _dateParseHandling.Value;
}
FloatParseHandling? previousFloatParseHandling = null;
if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling)
{
previousFloatParseHandling = reader.FloatParseHandling;
reader.FloatParseHandling = _floatParseHandling.Value;
}
int? previousMaxDepth = null;
if (_maxDepthSet && reader.MaxDepth != _maxDepth)
{
previousMaxDepth = reader.MaxDepth;
reader.MaxDepth = _maxDepth;
}
string previousDateFormatString = null;
if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
{
previousDateFormatString = reader.DateFormatString;
reader.DateFormatString = _dateFormatString;
}
CultureInfo previousCulture;
DateTimeZoneHandling? previousDateTimeZoneHandling;
DateParseHandling? previousDateParseHandling;
FloatParseHandling? previousFloatParseHandling;
int? previousMaxDepth;
string previousDateFormatString;
SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString);
TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
? new TraceJsonReader(reader)
@@ -730,6 +712,76 @@ namespace Newtonsoft.Json
if (traceJsonReader != null)
TraceWriter.Trace(TraceLevel.Verbose, "Deserialized JSON: " + Environment.NewLine + traceJsonReader.GetJson(), null);
ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
return value;
}
private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString)
{
if (_culture != null && !_culture.Equals(reader.Culture))
{
previousCulture = reader.Culture;
reader.Culture = _culture;
}
else
{
previousCulture = null;
}
if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
{
previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
reader.DateTimeZoneHandling = _dateTimeZoneHandling.Value;
}
else
{
previousDateTimeZoneHandling = null;
}
if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling)
{
previousDateParseHandling = reader.DateParseHandling;
reader.DateParseHandling = _dateParseHandling.Value;
}
else
{
previousDateParseHandling = null;
}
if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling)
{
previousFloatParseHandling = reader.FloatParseHandling;
reader.FloatParseHandling = _floatParseHandling.Value;
}
else
{
previousFloatParseHandling = null;
}
if (_maxDepthSet && reader.MaxDepth != _maxDepth)
{
previousMaxDepth = reader.MaxDepth;
reader.MaxDepth = _maxDepth;
}
else
{
previousMaxDepth = null;
}
if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
{
previousDateFormatString = reader.DateFormatString;
reader.DateFormatString = _dateFormatString;
}
else
{
previousDateFormatString = null;
}
}
private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString)
{
// reset reader back to previous options
if (previousCulture != null)
reader.Culture = previousCulture;
@@ -743,8 +795,6 @@ namespace Newtonsoft.Json
reader.MaxDepth = previousMaxDepth;
if (_dateFormatStringSet)
reader.DateFormatString = previousDateFormatString;
return value;
}
/// <summary>
+39 -13
View File
@@ -56,6 +56,7 @@ namespace Newtonsoft.Json
public class JsonTextReader : JsonReader, IJsonLineInfo
{
private const char UnicodeReplacementChar = '\uFFFD';
private const int MaximumJavascriptIntegerCharacterLength = 380;
private readonly TextReader _reader;
private char[] _chars;
@@ -1186,12 +1187,18 @@ namespace Newtonsoft.Json
{
string number = _stringReference.ToString();
// decimal.Parse doesn't support parsing hexadecimal values
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt32(number, 16)
: Convert.ToInt32(number, 8);
try
{
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt32(number, 16)
: Convert.ToInt32(number, 8);
numberValue = integer;
numberValue = integer;
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
@@ -1218,12 +1225,19 @@ namespace Newtonsoft.Json
{
string number = _stringReference.ToString();
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
try
{
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
numberValue = Convert.ToDecimal(integer);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
@@ -1250,9 +1264,17 @@ namespace Newtonsoft.Json
{
string number = _stringReference.ToString();
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
try
{
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
numberType = JsonToken.Integer;
}
else
@@ -1268,6 +1290,10 @@ namespace Newtonsoft.Json
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
string number = _stringReference.ToString();
if (number.Length > MaximumJavascriptIntegerCharacterLength)
throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
numberValue = BigInteger.Parse(number, CultureInfo.InvariantCulture);
numberType = JsonToken.Integer;
#else
+2 -3
View File
@@ -57,7 +57,6 @@ namespace Newtonsoft.Json
public string CurrentPropertyName { get; set; }
public int ArrayItemCount { get; set; }
public bool IsUniqueArray { get; set; }
public bool IsEnum { get; set; }
public IList<JToken> UniqueArrayItems { get; set; }
public JTokenWriter CurrentItemWriter { get; set; }
@@ -575,7 +574,7 @@ namespace Newtonsoft.Json
{
bool isInUniqueArray = (schemaScope.TokenType == JTokenType.Array && schemaScope.IsUniqueArray && schemaScope.ArrayItemCount > 0);
if (isInUniqueArray || schemaScope.IsEnum || schemas.Any(s => s.Enum != null))
if (isInUniqueArray || schemas.Any(s => s.Enum != null))
{
if (schemaScope.CurrentItemWriter == null)
{
@@ -602,7 +601,7 @@ namespace Newtonsoft.Json
schemaScope.UniqueArrayItems.Add(finishedItem);
}
else if (schemaScope.IsEnum || schemas.Any(s => s.Enum != null))
else if (schemas.Any(s => s.Enum != null))
{
foreach (JsonSchemaModel schema in schemas)
{
+2
View File
@@ -69,7 +69,9 @@ namespace Newtonsoft.Json.Linq
private static readonly JTokenType[] BooleanTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean };
private static readonly JTokenType[] NumberTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean };
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
private static readonly JTokenType[] BigIntegerTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean, JTokenType.Bytes };
#endif
private static readonly JTokenType[] StringTypes = new[] { JTokenType.Date, JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean, JTokenType.Bytes, JTokenType.Guid, JTokenType.TimeSpan, JTokenType.Uri };
private static readonly JTokenType[] GuidTypes = new[] { JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Guid, JTokenType.Bytes };
private static readonly JTokenType[] TimeSpanTypes = new[] { JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.TimeSpan };
@@ -18,7 +18,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
while (true)
{
if (container != null)
if (container != null && container.HasValues)
{
value = container.First;
}
@@ -224,17 +224,16 @@
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\CachedAttributeGetter.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
<Compile Include="Serialization\ReflectionValueProvider.cs" />
<Compile Include="Utilities\Base64Encoder.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\MethodCall.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\StringReference.cs" />
<Compile Include="Utilities\ThreadSafeStore.cs" />
<Compile Include="TypeNameHandling.cs" />
@@ -231,13 +231,11 @@
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\CachedAttributeGetter.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\ReflectionValueProvider.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
<Compile Include="Utilities\Base64Encoder.cs" />
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
@@ -248,6 +246,7 @@
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\MethodCall.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\StringReference.cs" />
<Compile Include="Utilities\ThreadSafeStore.cs" />
<Compile Include="TypeNameHandling.cs" />
@@ -231,13 +231,11 @@
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\CachedAttributeGetter.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\ReflectionValueProvider.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
<Compile Include="Utilities\Base64Encoder.cs" />
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
@@ -248,6 +246,7 @@
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\MethodCall.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\StringReference.cs" />
<Compile Include="Utilities\ThreadSafeStore.cs" />
<Compile Include="TypeNameHandling.cs" />
@@ -186,7 +186,6 @@
<Compile Include="Serialization\JsonSerializerProxy.cs" />
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\MemoryTraceWriter.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
@@ -209,7 +208,6 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
@@ -223,6 +221,7 @@
<Compile Include="Utilities\MethodCall.cs" />
<Compile Include="Utilities\MiscellaneousUtils.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringBuffer.cs" />
<Compile Include="Utilities\StringReference.cs" />
@@ -191,7 +191,6 @@
<Compile Include="Serialization\JsonSerializerProxy.cs" />
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\MemoryTraceWriter.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
@@ -213,7 +212,6 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
@@ -227,6 +225,7 @@
<Compile Include="Utilities\MethodCall.cs" />
<Compile Include="Utilities\MiscellaneousUtils.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringBuffer.cs" />
<Compile Include="Utilities\StringReference.cs" />
@@ -255,7 +255,6 @@
<Compile Include="Serialization\JsonSerializerProxy.cs" />
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
<Compile Include="Serialization\ReflectionValueProvider.cs" />
@@ -279,7 +278,6 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
@@ -293,6 +291,7 @@
<Compile Include="Utilities\MethodCall.cs" />
<Compile Include="Utilities\MiscellaneousUtils.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\ReflectionUtils.cs" />
<Compile Include="Utilities\StringBuffer.cs" />
<Compile Include="Utilities\StringReference.cs" />
+1 -2
View File
@@ -190,7 +190,6 @@
<Compile Include="Serialization\JsonSerializerProxy.cs" />
<Compile Include="Serialization\JsonStringContract.cs" />
<Compile Include="Serialization\JsonTypeReflector.cs" />
<Compile Include="Serialization\LateBoundMetadataTypeAttribute.cs" />
<Compile Include="Serialization\MemoryTraceWriter.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Serialization\OnErrorAttribute.cs" />
@@ -212,7 +211,7 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
+7 -228
View File
@@ -1,236 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Newtonsoft.Json.ruleset" ToolsVersion="12.0">
<IncludeAll Action="Warning" />
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1000" Action="None" />
<Rule Id="CA1001" Action="None" />
<Rule Id="CA1002" Action="None" />
<Rule Id="CA1003" Action="None" />
<Rule Id="CA1004" Action="None" />
<Rule Id="CA1005" Action="None" />
<Rule Id="CA1006" Action="None" />
<Rule Id="CA1007" Action="None" />
<Rule Id="CA1008" Action="None" />
<Rule Id="CA1009" Action="None" />
<Rule Id="CA1010" Action="None" />
<Rule Id="CA1011" Action="None" />
<Rule Id="CA1012" Action="None" />
<Rule Id="CA1013" Action="None" />
<Rule Id="CA1014" Action="None" />
<Rule Id="CA1016" Action="None" />
<Rule Id="CA1017" Action="None" />
<Rule Id="CA1018" Action="None" />
<Rule Id="CA1019" Action="None" />
<Rule Id="CA1020" Action="None" />
<Rule Id="CA1021" Action="None" />
<Rule Id="CA1023" Action="None" />
<Rule Id="CA1024" Action="None" />
<Rule Id="CA1025" Action="None" />
<Rule Id="CA1026" Action="None" />
<Rule Id="CA1027" Action="None" />
<Rule Id="CA1028" Action="None" />
<Rule Id="CA1030" Action="None" />
<Rule Id="CA1031" Action="None" />
<Rule Id="CA1032" Action="None" />
<Rule Id="CA1033" Action="None" />
<Rule Id="CA1034" Action="None" />
<Rule Id="CA1035" Action="None" />
<Rule Id="CA1036" Action="None" />
<Rule Id="CA1038" Action="None" />
<Rule Id="CA1039" Action="None" />
<Rule Id="CA1040" Action="None" />
<Rule Id="CA1041" Action="None" />
<Rule Id="CA1043" Action="None" />
<Rule Id="CA1044" Action="None" />
<Rule Id="CA1045" Action="None" />
<Rule Id="CA1046" Action="None" />
<Rule Id="CA1047" Action="None" />
<Rule Id="CA1048" Action="None" />
<Rule Id="CA1049" Action="None" />
<Rule Id="CA1050" Action="None" />
<Rule Id="CA1051" Action="None" />
<Rule Id="CA1052" Action="None" />
<Rule Id="CA1053" Action="None" />
<Rule Id="CA1054" Action="None" />
<Rule Id="CA1055" Action="None" />
<Rule Id="CA1056" Action="None" />
<Rule Id="CA1057" Action="None" />
<Rule Id="CA1058" Action="None" />
<Rule Id="CA1059" Action="None" />
<Rule Id="CA1060" Action="None" />
<Rule Id="CA1061" Action="None" />
<Rule Id="CA1062" Action="None" />
<Rule Id="CA1063" Action="None" />
<Rule Id="CA1064" Action="None" />
<Rule Id="CA1065" Action="None" />
<Rule Id="CA1300" Action="None" />
<Rule Id="CA1301" Action="None" />
<Rule Id="CA1302" Action="None" />
<Rule Id="CA1303" Action="None" />
<Rule Id="CA1304" Action="Error" />
<Rule Id="CA1305" Action="Error" />
<Rule Id="CA1306" Action="None" />
<Rule Id="CA1307" Action="None" />
<Rule Id="CA1308" Action="None" />
<Rule Id="CA1309" Action="None" />
<Rule Id="CA1400" Action="None" />
<Rule Id="CA1401" Action="None" />
<Rule Id="CA1402" Action="None" />
<Rule Id="CA1403" Action="None" />
<Rule Id="CA1404" Action="None" />
<Rule Id="CA1405" Action="None" />
<Rule Id="CA1406" Action="None" />
<Rule Id="CA1407" Action="None" />
<Rule Id="CA1408" Action="None" />
<Rule Id="CA1409" Action="None" />
<Rule Id="CA1410" Action="None" />
<Rule Id="CA1411" Action="None" />
<Rule Id="CA1412" Action="None" />
<Rule Id="CA1413" Action="None" />
<Rule Id="CA1414" Action="None" />
<Rule Id="CA1415" Action="None" />
<Rule Id="CA1500" Action="None" />
<Rule Id="CA1501" Action="None" />
<Rule Id="CA1502" Action="None" />
<Rule Id="CA1504" Action="None" />
<Rule Id="CA1505" Action="None" />
<Rule Id="CA1506" Action="None" />
<Rule Id="CA1600" Action="None" />
<Rule Id="CA1601" Action="None" />
<Rule Id="CA1700" Action="None" />
<Rule Id="CA1701" Action="None" />
<Rule Id="CA1702" Action="None" />
<Rule Id="CA1703" Action="None" />
<Rule Id="CA1704" Action="None" />
<Rule Id="CA1707" Action="None" />
<Rule Id="CA1708" Action="None" />
<Rule Id="CA1709" Action="None" />
<Rule Id="CA1710" Action="None" />
<Rule Id="CA1711" Action="None" />
<Rule Id="CA1712" Action="None" />
<Rule Id="CA1713" Action="None" />
<Rule Id="CA1714" Action="None" />
<Rule Id="CA1715" Action="None" />
<Rule Id="CA1716" Action="None" />
<Rule Id="CA1717" Action="None" />
<Rule Id="CA1719" Action="None" />
<Rule Id="CA1720" Action="None" />
<Rule Id="CA1721" Action="None" />
<Rule Id="CA1722" Action="None" />
<Rule Id="CA1724" Action="None" />
<Rule Id="CA1725" Action="None" />
<Rule Id="CA1726" Action="None" />
<Rule Id="CA1800" Action="None" />
<Rule Id="CA1801" Action="None" />
<Rule Id="CA1802" Action="None" />
<Rule Id="CA1804" Action="None" />
<Rule Id="CA1806" Action="None" />
<Rule Id="CA1809" Action="None" />
<Rule Id="CA1810" Action="None" />
<Rule Id="CA1811" Action="None" />
<Rule Id="CA1812" Action="None" />
<Rule Id="CA1813" Action="None" />
<Rule Id="CA1814" Action="None" />
<Rule Id="CA1815" Action="None" />
<Rule Id="CA1816" Action="None" />
<Rule Id="CA1819" Action="None" />
<Rule Id="CA1820" Action="None" />
<Rule Id="CA1821" Action="None" />
<Rule Id="CA1822" Action="None" />
<Rule Id="CA1823" Action="None" />
<Rule Id="CA1824" Action="None" />
<Rule Id="CA1900" Action="None" />
<Rule Id="CA1901" Action="None" />
<Rule Id="CA1307" Action="Error" />
<Rule Id="CA1308" Action="Error" />
<Rule Id="CA1309" Action="Error" />
<Rule Id="CA1804" Action="Warning" />
<Rule Id="CA1811" Action="Warning" />
<Rule Id="CA1812" Action="Warning" />
<Rule Id="CA1823" Action="Warning" />
<Rule Id="CA1903" Action="Error" />
<Rule Id="CA2000" Action="None" />
<Rule Id="CA2001" Action="None" />
<Rule Id="CA2002" Action="None" />
<Rule Id="CA2003" Action="None" />
<Rule Id="CA2004" Action="None" />
<Rule Id="CA2006" Action="None" />
<Rule Id="CA2100" Action="None" />
<Rule Id="CA2101" Action="None" />
<Rule Id="CA2102" Action="None" />
<Rule Id="CA2103" Action="None" />
<Rule Id="CA2104" Action="None" />
<Rule Id="CA2105" Action="None" />
<Rule Id="CA2106" Action="None" />
<Rule Id="CA2107" Action="None" />
<Rule Id="CA2108" Action="None" />
<Rule Id="CA2109" Action="None" />
<Rule Id="CA2111" Action="None" />
<Rule Id="CA2112" Action="None" />
<Rule Id="CA2114" Action="None" />
<Rule Id="CA2115" Action="None" />
<Rule Id="CA2116" Action="None" />
<Rule Id="CA2117" Action="None" />
<Rule Id="CA2118" Action="None" />
<Rule Id="CA2119" Action="None" />
<Rule Id="CA2120" Action="None" />
<Rule Id="CA2121" Action="None" />
<Rule Id="CA2122" Action="None" />
<Rule Id="CA2123" Action="None" />
<Rule Id="CA2124" Action="None" />
<Rule Id="CA2126" Action="None" />
<Rule Id="CA2130" Action="None" />
<Rule Id="CA2131" Action="None" />
<Rule Id="CA2132" Action="None" />
<Rule Id="CA2133" Action="None" />
<Rule Id="CA2134" Action="None" />
<Rule Id="CA2135" Action="None" />
<Rule Id="CA2136" Action="None" />
<Rule Id="CA2137" Action="None" />
<Rule Id="CA2138" Action="None" />
<Rule Id="CA2139" Action="None" />
<Rule Id="CA2140" Action="None" />
<Rule Id="CA2141" Action="None" />
<Rule Id="CA2142" Action="None" />
<Rule Id="CA2143" Action="None" />
<Rule Id="CA2144" Action="None" />
<Rule Id="CA2145" Action="None" />
<Rule Id="CA2146" Action="None" />
<Rule Id="CA2147" Action="None" />
<Rule Id="CA2149" Action="None" />
<Rule Id="CA2200" Action="None" />
<Rule Id="CA2201" Action="None" />
<Rule Id="CA2202" Action="None" />
<Rule Id="CA2204" Action="None" />
<Rule Id="CA2205" Action="None" />
<Rule Id="CA2207" Action="None" />
<Rule Id="CA2208" Action="None" />
<Rule Id="CA2210" Action="None" />
<Rule Id="CA2211" Action="None" />
<Rule Id="CA2212" Action="None" />
<Rule Id="CA2213" Action="None" />
<Rule Id="CA2214" Action="None" />
<Rule Id="CA2215" Action="None" />
<Rule Id="CA2216" Action="None" />
<Rule Id="CA2217" Action="None" />
<Rule Id="CA2218" Action="None" />
<Rule Id="CA2219" Action="None" />
<Rule Id="CA2220" Action="None" />
<Rule Id="CA2221" Action="None" />
<Rule Id="CA2222" Action="None" />
<Rule Id="CA2223" Action="None" />
<Rule Id="CA2224" Action="None" />
<Rule Id="CA2225" Action="None" />
<Rule Id="CA2226" Action="None" />
<Rule Id="CA2227" Action="None" />
<Rule Id="CA2228" Action="None" />
<Rule Id="CA2229" Action="None" />
<Rule Id="CA2230" Action="None" />
<Rule Id="CA2231" Action="None" />
<Rule Id="CA2232" Action="None" />
<Rule Id="CA2233" Action="None" />
<Rule Id="CA2234" Action="None" />
<Rule Id="CA2235" Action="None" />
<Rule Id="CA2236" Action="None" />
<Rule Id="CA2237" Action="None" />
<Rule Id="CA2238" Action="None" />
<Rule Id="CA2239" Action="None" />
<Rule Id="CA2240" Action="None" />
<Rule Id="CA2241" Action="None" />
<Rule Id="CA2242" Action="None" />
<Rule Id="CA2243" Action="None" />
</Rules>
</RuleSet>
@@ -91,5 +91,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.3.17312")]
[assembly: AssemblyFileVersion("6.0.3.17421")]
[assembly: CLSCompliant(true)]
@@ -166,7 +166,7 @@ namespace Newtonsoft.Json.Schema
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
@@ -176,7 +176,7 @@ namespace Newtonsoft.Json.Schema
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
@@ -192,7 +192,7 @@ namespace Newtonsoft.Json.Schema
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
@@ -278,7 +278,7 @@ namespace Newtonsoft.Json.Schema
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(type);
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
@@ -295,7 +295,7 @@ namespace Newtonsoft.Json.Schema
{
CurrentSchema.Enum = new List<JToken>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
@@ -371,7 +371,7 @@ namespace Newtonsoft.Json.Serialization
contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType, ignoreSerializableAttribute);
contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization));
JsonObjectAttribute attribute = JsonTypeReflector.GetJsonObjectAttribute(contract.NonNullableUnderlyingType);
JsonObjectAttribute attribute = JsonTypeReflector.GetCachedAttribute<JsonObjectAttribute>(contract.NonNullableUnderlyingType);
if (attribute != null)
contract.ItemRequired = attribute._itemRequired;
@@ -673,7 +673,7 @@ namespace Newtonsoft.Json.Serialization
/// <returns>The contract's default <see cref="JsonConverter" />.</returns>
protected virtual JsonConverter ResolveContractConverter(Type objectType)
{
return JsonTypeReflector.GetJsonConverter(objectType, objectType);
return JsonTypeReflector.GetJsonConverter(objectType);
}
private Func<object> GetDefaultCreator(Type createdType)
@@ -686,7 +686,7 @@ namespace Newtonsoft.Json.Serialization
#endif
private void InitializeContract(JsonContract contract)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.NonNullableUnderlyingType);
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(contract.NonNullableUnderlyingType);
if (containerAttribute != null)
{
contract.IsReference = containerAttribute._isReference;
@@ -916,9 +916,9 @@ namespace Newtonsoft.Json.Serialization
ConstructorInfo constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);
if (constructorInfo != null)
{
MethodCall<object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(constructorInfo);
ObjectConstructor<object> creator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(constructorInfo);
contract.ISerializableCreator = (args => methodCall(null, args));
contract.ISerializableCreator = creator;
}
return contract;
@@ -963,18 +963,19 @@ namespace Newtonsoft.Json.Serialization
/// <returns>A <see cref="JsonContract"/> for the given type.</returns>
protected virtual JsonContract CreateContract(Type objectType)
{
Type t = ReflectionUtils.EnsureNotNullableType(objectType);
if (IsJsonPrimitiveType(objectType))
return CreatePrimitiveContract(objectType);
if (JsonTypeReflector.GetJsonObjectAttribute(t) != null)
Type t = ReflectionUtils.EnsureNotNullableType(objectType);
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(t);
if (containerAttribute is JsonObjectAttribute)
return CreateObjectContract(objectType);
if (JsonTypeReflector.GetJsonArrayAttribute(t) != null)
if (containerAttribute is JsonArrayAttribute)
return CreateArrayContract(objectType);
if (JsonTypeReflector.GetJsonDictionaryAttribute(t) != null)
if (containerAttribute is JsonDictionaryAttribute)
return CreateDictionaryContract(objectType);
if (t == typeof(JToken) || t.IsSubclassOf(typeof(JToken)))
@@ -1133,7 +1134,7 @@ namespace Newtonsoft.Json.Serialization
else
valueProvider = new ReflectionValueProvider(member);
#elif !(PORTABLE40)
valueProvider = new ExpressionValueProvider(member);
valueProvider = new ExpressionValueProvider(member);
#else
valueProvider = new ReflectionValueProvider(member);
#endif
@@ -1252,8 +1253,8 @@ namespace Newtonsoft.Json.Serialization
// resolve converter for property
// the class type might have a converter but the property converter takes presidence
property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider);
property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider);
DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute<DefaultValueAttribute>(attributeProvider);
if (defaultValueAttribute != null)
@@ -1268,7 +1269,7 @@ namespace Newtonsoft.Json.Serialization
property.ItemIsReference = (propertyAttribute != null) ? propertyAttribute._itemIsReference : null;
property.ItemConverter =
(propertyAttribute != null && propertyAttribute.ItemConverterType != null)
? JsonConverterAttribute.CreateJsonConverterInstance(propertyAttribute.ItemConverterType)
? JsonTypeReflector.CreateJsonConverterInstance(propertyAttribute.ItemConverterType)
: null;
property.ItemReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._itemReferenceLoopHandling : null;
property.ItemTypeNameHandling = (propertyAttribute != null) ? propertyAttribute._itemTypeNameHandling : null;
@@ -105,7 +105,8 @@ namespace Newtonsoft.Json.Serialization
public override int GetHashCode()
{
return ((AssemblyName != null) ? AssemblyName.GetHashCode() : 0) ^ ((TypeName != null) ? TypeName.GetHashCode() : 0);
return ((AssemblyName != null) ? AssemblyName.GetHashCode() : 0)
^ ((TypeName != null) ? TypeName.GetHashCode() : 0);
}
public override bool Equals(object obj)
@@ -110,5 +110,4 @@ namespace Newtonsoft.Json.Serialization
}
}
}
#endif
@@ -57,11 +57,10 @@ namespace Newtonsoft.Json.Serialization
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly bool _isCollectionItemTypeNullableType;
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private MethodCall<object, object> _genericWrapperCreator;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
@@ -182,17 +181,16 @@ namespace Newtonsoft.Json.Serialization
CanDeserialize = canDeserialize;
if (CollectionItemType != null)
_isCollectionItemTypeNullableType = ReflectionUtils.IsNullableType(CollectionItemType);
#if (NET20 || NET35)
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (_isCollectionItemTypeNullableType
&& (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray)))
if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
{
ShouldCreateWrapper = true;
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray))
{
ShouldCreateWrapper = true;
}
}
#endif
@@ -224,10 +222,10 @@ namespace Newtonsoft.Json.Serialization
constructorArgument = _genericCollectionDefinitionType;
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor);
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(null, list);
return (IWrappedCollection)_genericWrapperCreator(list);
}
internal IList CreateTemporaryCollection()
@@ -100,12 +100,12 @@ namespace Newtonsoft.Json.Serialization
internal JsonContainerContract(Type underlyingType)
: base(underlyingType)
{
JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetJsonContainerAttribute(underlyingType);
JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(underlyingType);
if (jsonContainerAttribute != null)
{
if (jsonContainerAttribute.ItemConverterType != null)
ItemConverter = JsonConverterAttribute.CreateJsonConverterInstance(jsonContainerAttribute.ItemConverterType);
ItemConverter = JsonTypeReflector.CreateJsonConverterInstance(jsonContainerAttribute.ItemConverterType);
ItemIsReference = jsonContainerAttribute._itemIsReference;
ItemReferenceLoopHandling = jsonContainerAttribute._itemReferenceLoopHandling;
@@ -61,11 +61,10 @@ namespace Newtonsoft.Json.Serialization
internal JsonContract KeyContract { get; set; }
private readonly bool _isDictionaryValueTypeNullableType;
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private MethodCall<object, object> _genericWrapperCreator;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryDictionaryCreator;
@@ -134,18 +133,17 @@ namespace Newtonsoft.Json.Serialization
DictionaryKeyType = keyType;
DictionaryValueType = valueType;
if (DictionaryValueType != null)
_isDictionaryValueTypeNullableType = ReflectionUtils.IsNullableType(DictionaryValueType);
#if (NET20 || NET35)
Type tempDictioanryType;
// bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object
// wrapper will handle calling Add(T) instead
if (_isDictionaryValueTypeNullableType
&& (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)))
if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType))
{
ShouldCreateWrapper = true;
Type tempDictioanryType;
// bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType))
{
ShouldCreateWrapper = true;
}
}
#endif
@@ -168,10 +166,10 @@ namespace Newtonsoft.Json.Serialization
_genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType);
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor);
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(genericWrapperConstructor);
}
return (IWrappedDictionary)_genericWrapperCreator(null, dictionary);
return (IWrappedDictionary)_genericWrapperCreator(dictionary);
}
internal IDictionary CreateTemporaryDictionary()
@@ -39,10 +39,12 @@ namespace Newtonsoft.Json.Serialization
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
internal object _defaultValue;
private object _defaultValue;
private bool _hasGeneratedDefaultValue;
private string _propertyName;
private bool _skipPropertyNameEscape;
private Type _propertyType;
// use to cache contract during deserialization
internal JsonContract PropertyContract { get; set; }
@@ -109,7 +111,18 @@ namespace Newtonsoft.Json.Serialization
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType { get; set; }
public Type PropertyType
{
get { return _propertyType; }
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
@@ -154,7 +167,13 @@ namespace Newtonsoft.Json.Serialization
/// <value>The default value.</value>
public object DefaultValue
{
get { return _defaultValue; }
get
{
if (!_hasExplicitDefaultValue)
return null;
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
@@ -164,8 +183,14 @@ namespace Newtonsoft.Json.Serialization
internal object GetResolvedDefaultValue()
{
if (!_hasExplicitDefaultValue && PropertyType != null)
return ReflectionUtils.GetDefaultValue(PropertyType);
if (_propertyType == null)
return null;
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(PropertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
@@ -236,8 +236,11 @@ namespace Newtonsoft.Json.Serialization
if (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = (string)reader.Value;
if (!reader.Read())
break;
do
{
if (!reader.Read())
break;
} while (reader.TokenType == JsonToken.Comment);
if (CheckPropertyName(reader, propertyName))
continue;
@@ -245,6 +248,10 @@ namespace Newtonsoft.Json.Serialization
writer.WritePropertyName(propertyName);
writer.WriteToken(reader, true, true);
}
else if (reader.TokenType == JsonToken.Comment)
{
// eat
}
else
{
writer.WriteEndObject();
@@ -2020,7 +2027,7 @@ To fix this error either change the environment to be fully trusted, change the
if (property.PropertyContract == null)
property.PropertyContract = GetContractSafe(property.PropertyType);
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable)
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable && !property.Ignored)
property.ValueProvider.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType));
break;
case PropertyPresence.Null:
@@ -141,14 +141,15 @@ namespace Newtonsoft.Json.Serialization
return;
}
JsonConverter converter;
if ((((converter = (member != null) ? member.Converter : null) != null)
|| ((converter = (containerProperty != null) ? containerProperty.ItemConverter : null) != null)
|| ((converter = (containerContract != null) ? containerContract.ItemConverter : null) != null)
|| ((converter = valueContract.Converter) != null)
|| ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null)
|| ((converter = valueContract.InternalConverter) != null))
&& converter.CanWrite)
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
@@ -41,13 +41,6 @@ using System.Runtime.Serialization;
namespace Newtonsoft.Json.Serialization
{
#if !NET20 && !NETFX_CORE
internal interface IMetadataTypeAttribute
{
Type MetadataClassType { get; }
}
#endif
internal static class JsonTypeReflector
{
private static bool? _dynamicCodeGeneration;
@@ -62,8 +55,9 @@ namespace Newtonsoft.Json.Serialization
public const string ShouldSerializePrefix = "ShouldSerialize";
public const string SpecifiedPostfix = "Specified";
private static readonly ThreadSafeStore<object, Type> JsonConverterTypeCache = new ThreadSafeStore<object, Type>(GetJsonConverterTypeFromAttribute);
#if !(NET20 || NETFX_CORE || PORTABLE40 || PORTABLE)
private static readonly ThreadSafeStore<Type, Func<JsonConverter>> JsonConverterCreatorCache = new ThreadSafeStore<Type, Func<JsonConverter>>(GetJsonConverterCreator);
#if !(NET20 || NETFX_CORE)
private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
private const string MetadataTypeAttributeTypeName =
@@ -72,33 +66,11 @@ namespace Newtonsoft.Json.Serialization
private static Type _cachedMetadataTypeAttributeType;
#endif
public static JsonContainerAttribute GetJsonContainerAttribute(Type type)
public static T GetCachedAttribute<T>(object attributeProvider) where T : Attribute
{
return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type);
return CachedAttributeGetter<T>.GetAttribute(attributeProvider);
}
public static JsonObjectAttribute GetJsonObjectAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonObjectAttribute;
}
public static JsonArrayAttribute GetJsonArrayAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonArrayAttribute;
}
public static JsonDictionaryAttribute GetJsonDictionaryAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonDictionaryAttribute;
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
public static SerializableAttribute GetSerializableAttribute(Type type)
{
return CachedAttributeGetter<SerializableAttribute>.GetAttribute(type);
}
#endif
#if !NET20
public static DataContractAttribute GetDataContractAttribute(Type type)
{
@@ -151,7 +123,7 @@ namespace Newtonsoft.Json.Serialization
public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
{
JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);
JsonObjectAttribute objectAttribute = GetCachedAttribute<JsonObjectAttribute>(objectType);
if (objectAttribute != null)
return objectAttribute.MemberSerialization;
@@ -164,7 +136,7 @@ namespace Newtonsoft.Json.Serialization
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
if (!ignoreSerializableAttribute)
{
SerializableAttribute serializableAttribute = GetSerializableAttribute(objectType);
SerializableAttribute serializableAttribute = GetCachedAttribute<SerializableAttribute>(objectType);
if (serializableAttribute != null)
return MemberSerialization.Fields;
}
@@ -174,33 +146,48 @@ namespace Newtonsoft.Json.Serialization
return MemberSerialization.OptOut;
}
private static Type GetJsonConverterType(object attributeProvider)
public static JsonConverter GetJsonConverter(object attributeProvider)
{
return JsonConverterTypeCache.Get(attributeProvider);
}
JsonConverterAttribute converterAttribute = GetCachedAttribute<JsonConverterAttribute>(attributeProvider);
private static Type GetJsonConverterTypeFromAttribute(object attributeProvider)
{
JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider);
return (converterAttribute != null)
? converterAttribute.ConverterType
: null;
}
public static JsonConverter GetJsonConverter(object attributeProvider, Type targetConvertedType)
{
Type converterType = GetJsonConverterType(attributeProvider);
if (converterType != null)
if (converterAttribute != null)
{
JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);
return memberConverter;
Func<JsonConverter> creator = JsonConverterCreatorCache.Get(converterAttribute.ConverterType);
if (creator != null)
return creator();
}
return null;
}
public static JsonConverter CreateJsonConverterInstance(Type converterType)
{
Func<JsonConverter> converterCreator = JsonConverterCreatorCache.Get(converterType);
return converterCreator();
}
private static Func<JsonConverter> GetJsonConverterCreator(Type converterType)
{
Func<object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(converterType, false))
? ReflectionDelegateFactory.CreateDefaultConstructor<object>(converterType)
: null;
return () =>
{
try
{
if (defaultConstructor == null)
throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType));
return (JsonConverter)defaultConstructor();
}
catch (Exception ex)
{
throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType), ex);
}
};
}
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
public static TypeConverter GetTypeConverter(Type type)
{
@@ -208,27 +195,30 @@ namespace Newtonsoft.Json.Serialization
}
#endif
#if !(NET20 || NETFX_CORE || PORTABLE40 || PORTABLE)
#if !(NET20 || NETFX_CORE)
private static Type GetAssociatedMetadataType(Type type)
{
return AssociatedMetadataTypesCache.Get(type);
}
private static ReflectionObject _metadataTypeAttributeReflectionObject;
private static Type GetAssociateMetadataTypeFromAttribute(Type type)
{
Type metadataTypeAttributeType = GetMetadataTypeAttributeType();
if (metadataTypeAttributeType == null)
return null;
object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault();
Attribute attribute = ReflectionUtils.GetAttributes(type, metadataTypeAttributeType, true).SingleOrDefault();
if (attribute == null)
return null;
IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration)
? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute)
: new LateBoundMetadataTypeAttribute(attribute);
const string metadataClassTypeName = "MetadataClassType";
return metadataTypeAttribute.MetadataClassType;
if (_metadataTypeAttributeReflectionObject == null)
_metadataTypeAttributeReflectionObject = ReflectionObject.Create(metadataTypeAttributeType, metadataClassTypeName);
return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName);
}
private static Type GetMetadataTypeAttributeType()
@@ -253,7 +243,7 @@ namespace Newtonsoft.Json.Serialization
{
T attribute;
#if !(NET20 || NETFX_CORE || PORTABLE40 || PORTABLE)
#if !(NET20 || NETFX_CORE)
Type metadataType = GetAssociatedMetadataType(type);
if (metadataType != null)
{
@@ -281,7 +271,7 @@ namespace Newtonsoft.Json.Serialization
{
T attribute;
#if !(NET20 || NETFX_CORE || PORTABLE40 || PORTABLE)
#if !(NET20 || NETFX_CORE)
Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
if (metadataType != null)
{
@@ -388,15 +378,15 @@ namespace Newtonsoft.Json.Serialization
_fullyTrusted = appDomain.IsHomogenous && appDomain.IsFullyTrusted;
#else
try
{
new SecurityPermission(PermissionState.Unrestricted).Demand();
_fullyTrusted = true;
}
catch (Exception)
{
_fullyTrusted = false;
}
try
{
new SecurityPermission(PermissionState.Unrestricted).Demand();
_fullyTrusted = true;
}
catch (Exception)
{
_fullyTrusted = false;
}
#endif
}
@@ -414,7 +404,7 @@ namespace Newtonsoft.Json.Serialization
return LateBoundReflectionDelegateFactory.Instance;
#elif !(PORTABLE40)
return ExpressionReflectionDelegateFactory.Instance;
return ExpressionReflectionDelegateFactory.Instance;
#else
return LateBoundReflectionDelegateFactory.Instance;
#endif
@@ -1,60 +0,0 @@
#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
#if !NET20 && !NETFX_CORE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Reflection;
namespace Newtonsoft.Json.Serialization
{
internal class LateBoundMetadataTypeAttribute : IMetadataTypeAttribute
{
private static PropertyInfo _metadataClassTypeProperty;
private readonly object _attribute;
public LateBoundMetadataTypeAttribute(object attribute)
{
_attribute = attribute;
}
public Type MetadataClassType
{
get
{
if (_metadataClassTypeProperty == null)
_metadataClassTypeProperty = _attribute.GetType().GetProperty("MetadataClassType");
return (Type)ReflectionUtils.GetMemberValue(_metadataClassTypeProperty, _attribute);
}
}
}
}
#endif
@@ -160,6 +160,7 @@ namespace Newtonsoft.Json.Utilities
#endif
};
#if !(NETFX_CORE || PORTABLE)
private static readonly List<TypeInformation> PrimitiveTypeCodes = new List<TypeInformation>
{
new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty },
@@ -182,6 +183,7 @@ namespace Newtonsoft.Json.Utilities
new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, // no 17 in TypeCode for some reason
new TypeInformation { Type = typeof(string), TypeCode = PrimitiveTypeCode.String }
};
#endif
public static PrimitiveTypeCode GetTypeCode(Type t)
{
@@ -440,6 +442,12 @@ namespace Newtonsoft.Json.Utilities
return ConvertResult.Success;
}
if (initialValue is Guid && targetType == typeof(byte[]))
{
value = ((Guid)initialValue).ToByteArray();
return ConvertResult.Success;
}
if (initialValue is string)
{
if (targetType == typeof(Guid))
@@ -54,8 +54,6 @@ namespace Newtonsoft.Json.Utilities
LzHH_mm_ss = "HH:mm:ss".Length;
Lz_ = "-".Length;
Lz_zz = "-zz".Length;
Lz_zz_ = "-zz:".Length;
Lz_zz_zz = "-zz:zz".Length;
}
public int Year;
@@ -87,8 +85,6 @@ namespace Newtonsoft.Json.Utilities
private static readonly int LzHH_mm_ss;
private static readonly int Lz_;
private static readonly int Lz_zz;
private static readonly int Lz_zz_;
private static readonly int Lz_zz_zz;
private const short MaxFractionDigits = 7;
@@ -221,9 +221,15 @@ namespace Newtonsoft.Json.Utilities
private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator)
{
if (!fieldInfo.IsStatic)
{
generator.PushInstance(fieldInfo.DeclaringType);
generator.Emit(OpCodes.Ldfld, fieldInfo);
}
else
{
generator.Emit(OpCodes.Ldsfld, fieldInfo);
}
generator.Emit(OpCodes.Ldfld, fieldInfo);
generator.BoxIfNeeded(fieldInfo.FieldType);
generator.Return();
}
@@ -245,7 +251,12 @@ namespace Newtonsoft.Json.Utilities
generator.Emit(OpCodes.Ldarg_1);
generator.UnboxIfNeeded(fieldInfo.FieldType);
generator.Emit(OpCodes.Stfld, fieldInfo);
if (!fieldInfo.IsStatic)
generator.Emit(OpCodes.Stfld, fieldInfo);
else
generator.Emit(OpCodes.Stsfld, fieldInfo);
generator.Return();
}
@@ -1,266 +0,0 @@
#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
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal class DynamicWrapperBase
{
protected internal object UnderlyingObject;
}
internal static class DynamicWrapper
{
private static readonly object _lock = new object();
private static readonly WrapperDictionary _wrapperDictionary = new WrapperDictionary();
private static ModuleBuilder _moduleBuilder;
private static ModuleBuilder ModuleBuilder
{
get
{
Init();
return _moduleBuilder;
}
}
private static void Init()
{
if (_moduleBuilder == null)
{
lock (_lock)
{
if (_moduleBuilder == null)
{
AssemblyName assemblyName = new AssemblyName("Newtonsoft.Json.Dynamic");
assemblyName.KeyPair = new StrongNameKeyPair(GetStrongKey());
AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
_moduleBuilder = assembly.DefineDynamicModule("Newtonsoft.Json.DynamicModule", false);
}
}
}
}
private static byte[] GetStrongKey()
{
const string name = "Newtonsoft.Json.Dynamic.snk";
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
{
if (stream == null)
throw new MissingManifestResourceException("Should have " + name + " as an embedded resource.");
int length = (int)stream.Length;
byte[] buffer = new byte[length];
stream.Read(buffer, 0, length);
return buffer;
}
}
public static Type GetWrapper(Type interfaceType, Type realObjectType)
{
Type wrapperType = _wrapperDictionary.GetType(interfaceType, realObjectType);
if (wrapperType == null)
{
lock (_lock)
{
wrapperType = _wrapperDictionary.GetType(interfaceType, realObjectType);
if (wrapperType == null)
{
wrapperType = GenerateWrapperType(interfaceType, realObjectType);
_wrapperDictionary.SetType(interfaceType, realObjectType, wrapperType);
}
}
}
return wrapperType;
}
public static object GetUnderlyingObject(object wrapper)
{
DynamicWrapperBase wrapperBase = wrapper as DynamicWrapperBase;
if (wrapperBase == null)
throw new ArgumentException("Object is not a wrapper.", "wrapper");
return wrapperBase.UnderlyingObject;
}
private static Type GenerateWrapperType(Type interfaceType, Type underlyingType)
{
TypeBuilder wrapperBuilder = ModuleBuilder.DefineType(
"{0}_{1}_Wrapper".FormatWith(CultureInfo.InvariantCulture, interfaceType.Name, underlyingType.Name),
TypeAttributes.NotPublic | TypeAttributes.Sealed,
typeof(DynamicWrapperBase),
new[] { interfaceType });
WrapperMethodBuilder wrapperMethod = new WrapperMethodBuilder(underlyingType, wrapperBuilder);
foreach (MethodInfo method in interfaceType.GetAllMethods())
{
wrapperMethod.Generate(method);
}
return wrapperBuilder.CreateType();
}
public static T CreateWrapper<T>(object realObject) where T : class
{
var dynamicType = GetWrapper(typeof(T), realObject.GetType());
var dynamicWrapper = (DynamicWrapperBase)Activator.CreateInstance(dynamicType);
dynamicWrapper.UnderlyingObject = realObject;
return dynamicWrapper as T;
}
}
internal class WrapperMethodBuilder
{
private readonly Type _realObjectType;
private readonly TypeBuilder _wrapperBuilder;
public WrapperMethodBuilder(Type realObjectType, TypeBuilder proxyBuilder)
{
_realObjectType = realObjectType;
_wrapperBuilder = proxyBuilder;
}
public void Generate(MethodInfo newMethod)
{
if (newMethod.IsGenericMethod)
newMethod = newMethod.GetGenericMethodDefinition();
FieldInfo srcField = typeof(DynamicWrapperBase).GetField("UnderlyingObject", BindingFlags.Instance | BindingFlags.NonPublic);
var parameters = newMethod.GetParameters();
var parameterTypes = parameters.Select(parameter => parameter.ParameterType).ToArray();
MethodBuilder methodBuilder = _wrapperBuilder.DefineMethod(
newMethod.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
newMethod.ReturnType,
parameterTypes);
if (newMethod.IsGenericMethod)
{
methodBuilder.DefineGenericParameters(
newMethod.GetGenericArguments().Select(arg => arg.Name).ToArray());
}
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
LoadUnderlyingObject(ilGenerator, srcField);
PushParameters(parameters, ilGenerator);
ExecuteMethod(newMethod, parameterTypes, ilGenerator);
Return(ilGenerator);
}
private static void Return(ILGenerator ilGenerator)
{
ilGenerator.Emit(OpCodes.Ret);
}
private void ExecuteMethod(MethodBase newMethod, Type[] parameterTypes, ILGenerator ilGenerator)
{
MethodInfo srcMethod = GetMethod(newMethod, parameterTypes);
if (srcMethod == null)
throw new MissingMethodException("Unable to find method " + newMethod.Name + " on " + _realObjectType.FullName);
ilGenerator.Emit(OpCodes.Call, srcMethod);
}
private MethodInfo GetMethod(MethodBase realMethod, Type[] parameterTypes)
{
if (realMethod.IsGenericMethod)
return _realObjectType.GetGenericMethod(realMethod.Name, parameterTypes);
return _realObjectType.GetMethod(realMethod.Name, parameterTypes);
}
private static void PushParameters(ICollection<ParameterInfo> parameters, ILGenerator ilGenerator)
{
for (int i = 1; i < parameters.Count + 1; i++)
ilGenerator.Emit(OpCodes.Ldarg, i);
}
private static void LoadUnderlyingObject(ILGenerator ilGenerator, FieldInfo srcField)
{
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldfld, srcField);
}
}
internal class WrapperDictionary
{
private readonly Dictionary<string, Type> _wrapperTypes = new Dictionary<string, Type>();
private static string GenerateKey(Type interfaceType, Type realObjectType)
{
return interfaceType.Name + "_" + realObjectType.Name;
}
public Type GetType(Type interfaceType, Type realObjectType)
{
string key = GenerateKey(interfaceType, realObjectType);
if (_wrapperTypes.ContainsKey(key))
return _wrapperTypes[key];
return null;
}
public void SetType(Type interfaceType, Type realObjectType, Type wrapperType)
{
string key = GenerateKey(interfaceType, realObjectType);
if (_wrapperTypes.ContainsKey(key))
_wrapperTypes[key] = wrapperType;
else
_wrapperTypes.Add(key, wrapperType);
}
}
}
#endif
+4 -4
View File
@@ -47,7 +47,7 @@ namespace Newtonsoft.Json.Utilities
Type underlyingType = Enum.GetUnderlyingType(value.GetType());
ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
EnumValues<ulong> enumNameValues = GetNamesAndValues<T>();
IList<EnumValue<ulong>> enumNameValues = GetNamesAndValues<T>();
IList<T> selectedFlagsValues = new List<T>();
foreach (EnumValue<ulong> enumNameValue in enumNameValues)
@@ -66,7 +66,7 @@ namespace Newtonsoft.Json.Utilities
/// Gets a dictionary of the names and values of an Enum type.
/// </summary>
/// <returns></returns>
public static EnumValues<ulong> GetNamesAndValues<T>() where T : struct
public static IList<EnumValue<ulong>> GetNamesAndValues<T>() where T : struct
{
return GetNamesAndValues<ulong>(typeof(T));
}
@@ -76,7 +76,7 @@ namespace Newtonsoft.Json.Utilities
/// </summary>
/// <param name="enumType">The enum type to get names and values for.</param>
/// <returns></returns>
public static EnumValues<TUnderlyingType> GetNamesAndValues<TUnderlyingType>(Type enumType) where TUnderlyingType : struct
public static IList<EnumValue<TUnderlyingType>> GetNamesAndValues<TUnderlyingType>(Type enumType) where TUnderlyingType : struct
{
if (enumType == null)
throw new ArgumentNullException("enumType");
@@ -86,7 +86,7 @@ namespace Newtonsoft.Json.Utilities
IList<object> enumValues = GetValues(enumType);
IList<string> enumNames = GetNames(enumType);
EnumValues<TUnderlyingType> nameValues = new EnumValues<TUnderlyingType>();
IList<EnumValue<TUnderlyingType>> nameValues = new List<EnumValue<TUnderlyingType>>();
for (int i = 0; i < enumValues.Count; i++)
{
+35 -35
View File
@@ -1,37 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
//#region License
//// Copyright (c) 2007 James Newton-King
////
//// Permission is hereby granted, free of charge, to any person
//// obtaining a copy of this software and associated documentation
//// files (the "Software"), to deal in the Software without
//// restriction, including without limitation the rights to use,
//// copy, modify, merge, publish, distribute, sublicense, and/or sell
//// copies of the Software, and to permit persons to whom the
//// Software is furnished to do so, subject to the following
//// conditions:
////
//// The above copyright notice and this permission notice shall be
//// included in all copies or substantial portions of the Software.
////
//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//// OTHER DEALINGS IN THE SOFTWARE.
//#endregion
using System.Collections.ObjectModel;
//using System.Collections.ObjectModel;
namespace Newtonsoft.Json.Utilities
{
internal class EnumValues<T> : KeyedCollection<string, EnumValue<T>> where T : struct
{
protected override string GetKeyForItem(EnumValue<T> item)
{
return item.Name;
}
}
}
//namespace Newtonsoft.Json.Utilities
//{
// internal class EnumValues<T> : KeyedCollection<string, EnumValue<T>> where T : struct
// {
// protected override string GetKeyForItem(EnumValue<T> item)
// {
// return item.Name;
// }
// }
//}
@@ -71,5 +71,4 @@ namespace Newtonsoft.Json.Utilities
}
}
}
#endif
@@ -0,0 +1,155 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal class ReflectionMember
{
public Type MemberType { get; set; }
public Func<object, object> Getter { get; set; }
public Action<object, object> Setter { get; set; }
}
internal class ReflectionObject
{
public ObjectConstructor<object> Creator { get; private set; }
public IDictionary<string, ReflectionMember> Members { get; private set; }
public ReflectionObject()
{
Members = new Dictionary<string, ReflectionMember>();
}
public object GetValue(object target, string member)
{
Func<object, object> getter = Members[member].Getter;
return getter(target);
}
public void SetValue(object target, string member, object value)
{
Action<object, object> setter = Members[member].Setter;
setter(target, value);
}
public Type GetType(string member)
{
return Members[member].MemberType;
}
public static ReflectionObject Create(Type t, params string[] memberNames)
{
return Create(t, null, memberNames);
}
public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames)
{
ReflectionObject d = new ReflectionObject();
ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory;
if (creator != null)
{
d.Creator = delegateFactory.CreateParametrizedConstructor(creator);
}
else
{
if (ReflectionUtils.HasDefaultConstructor(t, false))
{
Func<object> ctor = delegateFactory.CreateDefaultConstructor<object>(t);
d.Creator = args => ctor();
}
}
foreach (string memberName in memberNames)
{
MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public);
if (members.Length != 1)
throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName));
MemberInfo member = members.Single();
ReflectionMember reflectionMember = new ReflectionMember();
switch (member.MemberType())
{
case MemberTypes.Field:
case MemberTypes.Property:
if (ReflectionUtils.CanReadMemberValue(member, false))
reflectionMember.Getter = delegateFactory.CreateGet<object>(member);
if (ReflectionUtils.CanSetMemberValue(member, false, false))
reflectionMember.Setter = delegateFactory.CreateSet<object>(member);
break;
case MemberTypes.Method:
MethodInfo method = (MethodInfo)member;
if (method.IsPublic)
{
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0 && method.ReturnType != typeof(void))
{
MethodCall<object, object> call = delegateFactory.CreateMethodCall<object>(method);
reflectionMember.Getter = target => call(target);
}
else if (parameters.Length == 1 && method.ReturnType == typeof(void))
{
MethodCall<object, object> call = delegateFactory.CreateMethodCall<object>(method);
reflectionMember.Setter = (target, arg) => call(target, arg);
}
}
break;
default:
throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name));
}
if (ReflectionUtils.CanReadMemberValue(member, false))
reflectionMember.Getter = delegateFactory.CreateGet<object>(member);
if (ReflectionUtils.CanSetMemberValue(member, false, false))
reflectionMember.Setter = delegateFactory.CreateSet<object>(member);
reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member);
d.Members[memberName] = reflectionMember;
}
return d;
}
}
}
@@ -429,6 +429,8 @@ namespace Newtonsoft.Json.Utilities
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member");
}
@@ -671,6 +673,11 @@ namespace Newtonsoft.Json.Utilities
#if !(NETFX_CORE || PORTABLE)
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
return (T[])GetAttributes(attributeProvider, typeof(T), inherit);
}
public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit)
{
ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider");
@@ -680,44 +687,50 @@ namespace Newtonsoft.Json.Utilities
// ICustomAttributeProvider doesn't do inheritance
if (provider is Type)
return (T[])((Type)provider).GetCustomAttributes(typeof(T), inherit);
return (Attribute[])((Type)provider).GetCustomAttributes(attributeType, inherit);
if (provider is Assembly)
return (T[])Attribute.GetCustomAttributes((Assembly)provider, typeof(T));
return Attribute.GetCustomAttributes((Assembly)provider, attributeType);
if (provider is MemberInfo)
return (T[])Attribute.GetCustomAttributes((MemberInfo)provider, typeof(T), inherit);
return Attribute.GetCustomAttributes((MemberInfo)provider, attributeType, inherit);
#if !PORTABLE40
if (provider is Module)
return (T[])Attribute.GetCustomAttributes((Module)provider, typeof(T), inherit);
return Attribute.GetCustomAttributes((Module)provider, attributeType, inherit);
#endif
if (provider is ParameterInfo)
return (T[])Attribute.GetCustomAttributes((ParameterInfo)provider, typeof(T), inherit);
return Attribute.GetCustomAttributes((ParameterInfo)provider, attributeType, inherit);
#if !PORTABLE40
return (T[])((ICustomAttributeProvider)attributeProvider).GetCustomAttributes(typeof(T), inherit);
#endif
return (Attribute[])((ICustomAttributeProvider)attributeProvider).GetCustomAttributes(attributeType, inherit);
#else
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
#endif
}
#else
public static T[] GetAttributes<T>(object provider, bool inherit) where T : Attribute
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
return GetAttributes(attributeProvider, typeof(T), inherit).Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit)
{
if (provider is Type)
return ((Type) provider).GetTypeInfo().GetCustomAttributes<T>(inherit).ToArray();
return ((Type) provider).GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray();
if (provider is Assembly)
return ((Assembly) provider).GetCustomAttributes<T>().ToArray();
return ((Assembly) provider).GetCustomAttributes(attributeType).ToArray();
if (provider is MemberInfo)
return ((MemberInfo) provider).GetCustomAttributes<T>(inherit).ToArray();
return ((MemberInfo) provider).GetCustomAttributes(attributeType, inherit).ToArray();
if (provider is Module)
return ((Module) provider).GetCustomAttributes<T>().ToArray();
return ((Module) provider).GetCustomAttributes(attributeType).ToArray();
if (provider is ParameterInfo)
return ((ParameterInfo) provider).GetCustomAttributes<T>(inherit).ToArray();
return ((ParameterInfo) provider).GetCustomAttributes(attributeType, inherit).ToArray();
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
}
@@ -796,6 +809,7 @@ namespace Newtonsoft.Json.Utilities
return fieldInfos.Cast<FieldInfo>();
}
#if !(NETFX_CORE || PORTABLE)
private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private FieldInfos only being returned for the current Type
@@ -815,6 +829,7 @@ namespace Newtonsoft.Json.Utilities
}
}
}
#endif
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
@@ -571,54 +571,5 @@ namespace Newtonsoft.Json.Utilities
Type match;
return type.AssignableToTypeName(fullTypeName, out match);
}
public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes)
{
var methods = type.GetMethods().Where(method => method.Name == name);
foreach (var method in methods)
{
if (method.HasParameters(parameterTypes))
return method;
}
return null;
}
public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes)
{
var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray();
if (methodParameters.Length != parameterTypes.Length)
return false;
for (int i = 0; i < methodParameters.Length; i++)
if (methodParameters[i].ToString() != parameterTypes[i].ToString())
return false;
return true;
}
public static IEnumerable<Type> GetAllInterfaces(this Type target)
{
foreach (var i in target.GetInterfaces())
{
yield return i;
foreach (var ci in i.GetInterfaces())
{
yield return ci;
}
}
}
public static IEnumerable<MethodInfo> GetAllMethods(this Type target)
{
var allTypes = target.GetAllInterfaces().ToList();
allTypes.Add(target);
return from type in allTypes
from method in type.GetMethods()
select method;
}
}
}
Binary file not shown.
-16
View File
@@ -1,16 +0,0 @@
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>FSharp.Core</id>
<version>4.0.0</version>
<title>FSharp.Core</title>
<authors>Microsoft</authors>
<owners>Microsoft</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>FSharp.Core.dll</description>
<releaseNotes>V 4.0.0</releaseNotes>
<copyright>Copyright 2012</copyright>
<language />
<tags>f#</tags>
</metadata>
</package>
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -1,79 +0,0 @@
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033\deflangfe1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Tahoma;}{\f1\fnil\fcharset2 Symbol;}}
{\colortbl ;\red0\green0\blue255;}
{\stylesheet{ Normal;}{\s1 heading 1;}{\s2 heading 2;}}
{\*\generator Riched20 6.2.9200}{\*\mmathPr\mdispDef1\mwrapIndent1440 }\viewkind4\uc1
\pard\nowidctlpar\sb120\sa120\b\f0\fs20 TODO: Replace with updated license.\par
MICROSOFT PRE-RELEASE SOFTWARE LICENSE TERMS\par
.NET FRAMEWORK .DLL PROTOTYPE(S)\fs21\par
\pard\brdrb\brdrs\brdrw10\brsp20 \nowidctlpar\sb120\sa120\fs20\par
\pard\nowidctlpar\sb120\sa120\b0 These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the pre-release software named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft\par
\pard{\pntext\f1\'B7\tab}{\*\pn\pnlvlblt\pnf1\pnindent360{\pntxtb\'B7}}\nowidctlpar\fi-360\li360\sb120\sa120 updates,\par
{\pntext\f1\'B7\tab}supplements,\par
{\pntext\f1\'B7\tab}Internet-based services, and\par
{\pntext\f1\'B7\tab}support services\par
\pard\nowidctlpar\sb120\sa120 for this software, unless other terms accompany those items. If so, those terms apply.\par
\b BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE.\par
\pard\brdrt\brdrs\brdrw10\brsp20 \nowidctlpar\sb120\sa120 If you comply with these license terms, you have the rights below.\par
\pard
{\pntext\f0 1.\tab}{\*\pn\pnlvlbody\pnf0\pnindent360\pnstart1\pndec{\pntxta.}}
\nowidctlpar\s1\fi-357\li357\sb120\sa120 INSTALLATION AND USE RIGHTS. \par
\pard{\pntext\f1\'B7\tab}{\*\pn\pnlvlblt\pnf1\pnindent357{\pntxtb\'B7}}\nowidctlpar\fi-357\li720\sb120\sa120\b0 You may install and use any number of copies of the software on your premises to design, develop and test your programs for use with the software. \par
{\pntext\f1\'B7\tab}Evaluation Only. You may not test or deploy the software in a live operating environment unless Microsoft permits you to do so under another agreement.\par
\pard\nowidctlpar\s1\fi-357\li357\sb120\sa120\b 2.\tab PRE-RELEASE SOFTWARE. \b0 This software is a pre-release version. It may not work the way a final version of the software will. We may change it for the final, commercial version. We also may not release a commercial version.\par
\b 3.\tab FEEDBACK. \b0 If you give feedback about the software to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement.\par
\b 4.\tab SCOPE OF LICENSE.\b0 The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not\par
\pard{\pntext\f1\'B7\tab}{\*\pn\pnlvlblt\pnf1\pnindent363{\pntxtb\'B7}}\nowidctlpar\fi-363\li720\sb120\sa120 work around any technical limitations in the software;\par
{\pntext\f1\'B7\tab}reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation;\par
{\pntext\f1\'B7\tab}make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation;\par
{\pntext\f1\'B7\tab}publish the software for others to copy;\par
{\pntext\f1\'B7\tab}rent, lease or lend the software;\par
{\pntext\f1\'B7\tab}transfer the software or this agreement to any third party; or\par
{\pntext\f1\'B7\tab}use the software for commercial software hosting services.\par
\pard\nowidctlpar\s1\fi-357\li357\sb120\sa120\b 5.\tab EXPORT RESTRICTIONS.\b0 The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see {\cf1\ul{\field{\*\fldinst{HYPERLINK "http://www.microsoft.com/exporting"}}{\fldrslt{www.microsoft.com/exporting}}}}\f0\fs20 .\ul\par
\ulnone\b 6.\tab SUPPORT SERVICES. \b0 Because this software is \ldblquote as is,\rdblquote we may not provide support services for it.\par
\b 7.\tab ENTIRE AGREEMENT.\b0 This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services.\par
\pard\nowidctlpar\s1\fi-360\li360\sb120\sa120\b 8.\tab APPLICABLE LAW.\par
\pard\nowidctlpar\s2\fi-363\li720\sb120\sa120 a.\tab United States.\b0 If you acquired the software in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.\par
\b b.\tab Outside the United States.\b0 If you acquired the software in any other country, the laws of that country apply.\par
\pard\nowidctlpar\s1\fi-357\li357\sb120\sa120\b 9.\tab LEGAL EFFECT.\b0 This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.\par
\b 10.\tab DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED \ldblquote AS-IS.\rdblquote YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\par
\tab FOR AUSTRALIA \endash YOU HAVE STATUTORY GUARANTEES UNDER THE AUSTRALIAN CONSUMER LAW AND NOTHING IN THESE TERMS IS INTENDED TO AFFECT THOSE RIGHTS.\b0\par
\pard\nowidctlpar\fs24\par
\pard\widctlpar\s1\fi-357\li357\sb120\sa120\b\fs20 11.\tab LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.\par
\pard\nowidctlpar\li357\sb120\sa120\b0 This limitation applies to\par
\pard{\pntext\f1\'B7\tab}{\*\pn\pnlvlblt\pnf1\pnindent363{\pntxtb\'B7}}\nowidctlpar\fi-363\li720\sb120\sa120 anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and\par
{\pntext\f1\'B7\tab}claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.\par
\pard\nowidctlpar\li360\sb120\sa120 It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.\par
\pard\nowidctlpar\sb120\sa120\b Please note: As this software is distributed in Quebec, Canada, some of the clauses in this agreement are provided below in French.\par
\lang1036 Remarque : Ce logiciel \'e9tant distribu\'e9 au Qu\'e9bec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en fran\'e7ais.\par
EXON\'c9RATION DE GARANTIE.\b0 Le logiciel vis\'e9 par une licence est offert \'ab tel quel \'bb. Toute utilisation de ce logiciel est \'e0 votre seule risque et p\'e9ril. Microsoft n\rquote accorde aucune autre garantie expresse. Vous pouvez b\'e9n\'e9ficier de droits additionnels en vertu du droit local sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualit\'e9 marchande, d\rquote ad\'e9quation \'e0 un usage particulier et d\rquote absence de contrefa\'e7on sont exclues.\par
\b LIMITATION DES DOMMAGES-INT\'c9R\'caTS ET EXCLUSION DE RESPONSABILIT\'c9 POUR LES DOMMAGES.\b0 Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement \'e0 hauteur de 5,00 $ US. Vous ne pouvez pr\'e9tendre \'e0 aucune indemnisation pour les autres dommages, y compris les dommages sp\'e9ciaux, indirects ou accessoires et pertes de b\'e9n\'e9fices.\par
\lang1033 Cette limitation concerne :\par
\pard{\pntext\f1\'B7\tab}{\*\pn\pnlvlblt\pnf1\pnindent360{\pntxtb\'B7}}\nowidctlpar\fi-360\li360\sb120\sa120\lang1036 tout ce qui est reli\'e9 au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et\par
{\pntext\f1\'B7\tab}les r\'e9clamations au titre de violation de contrat ou de garantie, ou au titre de responsabilit\'e9 stricte, de n\'e9gligence ou d\rquote une autre faute dans la limite autoris\'e9e par la loi en vigueur.\par
\pard\nowidctlpar\sb120\sa120 Elle s\rquote applique \'e9galement, m\'eame si Microsoft connaissait ou devrait conna\'eetre l\rquote\'e9ventualit\'e9 d\rquote un tel dommage. Si votre pays n\rquote autorise pas l\rquote exclusion ou la limitation de responsabilit\'e9 pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l\rquote exclusion ci-dessus ne s\rquote appliquera pas \'e0 votre \'e9gard.\par
\pard\widctlpar\sb120\sa120\b EFFET JURIDIQUE.\b0 Le pr\'e9sent contrat d\'e9crit certains droits juridiques. Vous pourriez avoir d\rquote autres droits pr\'e9vus par les lois de votre pays. Le pr\'e9sent contrat ne modifie pas les droits que vous conf\'e8rent les lois de votre pays si celles-ci ne le permettent pas.\fs19\lang1033\par
}
Binary file not shown.
-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>NUnit</id>
<version>2.6.2</version>
<title>NUnit</title>
<authors>Charlie Poole</authors>
<owners>Charlie Poole</owners>
<licenseUrl>http://nunit.org/nuget/license.html</licenseUrl>
<projectUrl>http://nunit.org/</projectUrl>
<iconUrl>http://nunit.org/nuget/nunit_32x32.png</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>NUnit features a fluent assert syntax, parameterized, generic and theory tests and is user-extensible. A number of runners, both from the NUnit project and by third parties, are able to execute NUnit tests.
Version 2.6 is the seventh major release of this well-known and well-tested programming tool.
This package includes only the framework assembly. You will need to install the NUnit.Runners package unless you are using a third-party runner.</description>
<summary>NUnit is a unit-testing framework for all .Net languages with a strong TDD focus.</summary>
<releaseNotes>Version 2.6 is the seventh major release of NUnit.
Unlike earlier versions, this package includes only the framework assembly. You will need to install the NUnit.Runners package unless you are using a third-party runner.
The nunit.mocks assembly is now provided by the NUnit.Mocks package. The pnunit.framework assembly is provided by the pNUnit package.</releaseNotes>
<copyright />
<language>en-US</language>
<tags>test testing tdd framework fluent assert theory plugin addin</tags>
</metadata>
</package>
Binary file not shown.
File diff suppressed because it is too large Load Diff
-15
View File
@@ -1,15 +0,0 @@
Copyright © 2002-2012 Charlie Poole
Copyright © 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov
Copyright © 2000-2002 Philip A. Craig
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment (see the following) in the product documentation is required.
Portions Copyright © 2002-2012 Charlie Poole or Copyright © 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov or Copyright © 2000-2002 Philip A. Craig
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.