Merge remote-tracking branch 'origin/json-schema'

This commit is contained in:
James Newton-King
2014-12-22 14:36:41 +13:00
60 changed files with 2326 additions and 1552 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[Bb]in/
[Oo]bj/
[Ww]orking/
[Ww]orking*/
Build/runbuild.txt
Doc/doc.shfbproj_*
TestResults/
+1 -1
View File
@@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>Newtonsoft.Json</id>
<version>6.0.6</version>
<version>6.0.7</version>
<title>Json.NET</title>
<description>Json.NET is a popular high-performance JSON framework for .NET</description>
<authors>James Newton-King</authors>
+8 -6
View File
@@ -1,13 +1,14 @@
properties {
$zipFileName = "Json60r6.zip"
$zipFileName = "Json60r7.zip"
$majorVersion = "6.0"
$majorWithReleaseVersion = "6.0.6"
$majorWithReleaseVersion = "6.0.7"
$version = GetVersion $majorWithReleaseVersion
$signAssemblies = $false
$signKeyPath = "C:\Development\Releases\newtonsoft.snk"
$buildDocumentation = $false
$buildNuGet = $true
$treatWarningsAsErrors = $false
$workingName = if ($workingName) {$workingName} else {"Working"}
$baseDir = resolve-path ..
$buildDir = "$baseDir\Build"
@@ -15,12 +16,12 @@
$toolsDir = "$baseDir\Tools"
$docDir = "$baseDir\Doc"
$releaseDir = "$baseDir\Release"
$workingDir = "$baseDir\Working"
$workingDir = "$baseDir\$workingName"
$builds = @(
@{Name = "Newtonsoft.Json"; TestsName = "Newtonsoft.Json.Tests"; TestsFunction = "NUnitTests"; Constants=""; FinalDir="Net45"; NuGetDir = "net45"; Framework="net-4.0"; Sign=$true},
@{Name = "Newtonsoft.Json.Portable"; TestsName = "Newtonsoft.Json.Tests.Portable"; TestsFunction = "NUnitTests"; Constants="PORTABLE"; FinalDir="Portable"; NuGetDir = "portable-net45+wp80+win8+wpa81+aspnetcore50"; Framework="net-4.0"; Sign=$true},
@{Name = "Newtonsoft.Json.Portable40"; TestsName = "Newtonsoft.Json.Tests.Portable40"; TestsFunction = "NUnitTests"; Constants="PORTABLE40"; FinalDir="Portable40"; NuGetDir = "portable-net40+sl5+wp80+win8+wpa81"; Framework="net-4.0"; Sign=$true},
@{Name = $null; TestsName = "Newtonsoft.Json.Tests.AspNetCore50"; TestsFunction = "CoreClrTests"; Constants="ASPNETCORE50"; FinalDir="ASPNETCORE50"; NuGetDir = $null; Framework=$null; Sign=$null},
#@{Name = $null; TestsName = "Newtonsoft.Json.Tests.AspNetCore50"; TestsFunction = "CoreClrTests"; Constants="ASPNETCORE50"; FinalDir="ASPNETCORE50"; NuGetDir = $null; Framework=$null; Sign=$null},
@{Name = "Newtonsoft.Json.WinRT"; TestsName = "Newtonsoft.Json.Tests.WinRT"; TestsFunction = "WinRTTests"; Constants="NETFX_CORE"; FinalDir="WinRT"; NuGetDir = "netcore45"; Framework="net-4.5"; Sign=$true},
@{Name = "Newtonsoft.Json.Net40"; TestsName = "Newtonsoft.Json.Tests.Net40"; TestsFunction = "NUnitTests"; Constants="NET40"; FinalDir="Net40"; NuGetDir = "net40"; Framework="net-4.0"; Sign=$true},
@{Name = "Newtonsoft.Json.Net35"; TestsName = "Newtonsoft.Json.Tests.Net35"; TestsFunction = "NUnitTests"; Constants="NET35"; FinalDir="Net35"; NuGetDir = "net35"; Framework="net-2.0"; Sign=$true},
@@ -28,7 +29,7 @@
)
}
$framework = '4.0x86'
framework '4.0x86'
task default -depends Test
@@ -38,11 +39,12 @@ task Clean {
if (Test-Path -path $workingDir)
{
Write-Output "Deleting Working Directory"
Write-Output "Deleting existing working directory $workingDir"
del $workingDir -Recurse -Force
}
Write-Output "Creating working directory $workingDir"
New-Item -Path $workingDir -ItemType Directory
}
@@ -33,4 +33,4 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.6.17929")]
[assembly: AssemblyFileVersion("6.0.7.18022")]
@@ -462,6 +462,85 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("234", ds.Customers[0].CustomerID);
}
[Test]
public void ContractResolverInsideConverter()
{
var test = new MultipleDataTablesJsonTest
{
TableWrapper1 = new DataTableWrapper { DataTableProperty = CreateDataTable(3, "Table1Col") },
TableWrapper2 = new DataTableWrapper { DataTableProperty = CreateDataTable(3, "Table2Col") }
};
string json = JsonConvert.SerializeObject(test, Formatting.Indented, new LowercaseDataTableConverter());
Assert.AreEqual(@"{
""TableWrapper1"": {
""DataTableProperty"": [
{
""table1col1"": ""1"",
""table1col2"": ""2"",
""table1col3"": ""3""
}
],
""StringProperty"": null,
""IntProperty"": 0
},
""TableWrapper2"": {
""DataTableProperty"": [
{
""table2col1"": ""1"",
""table2col2"": ""2"",
""table2col3"": ""3""
}
],
""StringProperty"": null,
""IntProperty"": 0
}
}", json);
}
private static DataTable CreateDataTable(int cols, string colNamePrefix)
{
var table = new DataTable();
for (int i = 1; i <= cols; i++)
{
table.Columns.Add(new DataColumn() { ColumnName = colNamePrefix + i, DefaultValue = i });
}
table.Rows.Add(table.NewRow());
return table;
}
public class DataTableWrapper
{
public DataTable DataTableProperty { get; set; }
public String StringProperty { get; set; }
public Int32 IntProperty { get; set; }
}
public class MultipleDataTablesJsonTest
{
public DataTableWrapper TableWrapper1 { get; set; }
public DataTableWrapper TableWrapper2 { get; set; }
}
public class LowercaseDataTableConverter : DataTableConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dataTableSerializer = new JsonSerializer { ContractResolver = new LowercaseContractResolver() };
base.WriteJson(writer, value, dataTableSerializer);
}
}
public class LowercaseContractResolver : DefaultContractResolver
{
protected internal override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
}
}
@@ -491,7 +491,7 @@ namespace Newtonsoft.Json.Tests.Converters
Value2 = DuplicateNameEnum2.foo_bar_NOT_USED
});
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
string xml = @"<DuplicateEnumNameTestClass xmlns=""http://schemas.datacontract.org/2004/07/Newtonsoft.Json.Tests.Converters"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<Value>foo_bar</Value>
@@ -825,6 +825,49 @@ namespace Newtonsoft.Json.Tests
]", sb.ToString());
}
[Test]
public void WriteTokenDirect()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(JsonToken.StartArray);
jsonWriter.WriteToken(JsonToken.Integer, 1);
jsonWriter.WriteToken(JsonToken.StartObject);
jsonWriter.WriteToken(JsonToken.PropertyName, "string");
jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue);
jsonWriter.WriteToken(JsonToken.EndObject);
jsonWriter.WriteToken(JsonToken.EndArray);
}
Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString());
}
[Test]
public void WriteTokenDirect_BadValue()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(JsonToken.StartArray);
ExceptionAssert.Throws<FormatException>(() =>
{
jsonWriter.WriteToken(JsonToken.Integer, "three");
}, "Input string was not in a correct format.");
ExceptionAssert.Throws<ArgumentNullException>(() =>
{
jsonWriter.WriteToken(JsonToken.Integer);
}, @"Value cannot be null.
Parameter name: value");
}
}
[Test]
public void BadWriteEndArray()
{
@@ -0,0 +1,250 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class AnnotationsTests : TestFixtureBase
{
[Test]
public void AddAnnotation()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
string s = o.Annotation<string>();
Assert.AreEqual("A string!", s);
s = (string)o.Annotation(typeof(string));
Assert.AreEqual("A string!", s);
}
[Test]
public void AddAnnotation_MultipleOfTheSameType()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation("Another string!");
string s = o.Annotation<string>();
Assert.AreEqual("A string!", s);
s = (string)o.Annotation(typeof(string));
Assert.AreEqual("A string!", s);
}
[Test]
public void AddAnnotation_MultipleOfDifferentTypes()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation(new Uri("http://www.google.com/"));
string s = o.Annotation<string>();
Assert.AreEqual("A string!", s);
s = (string)o.Annotation(typeof(string));
Assert.AreEqual("A string!", s);
Uri i = o.Annotation<Uri>();
Assert.AreEqual(new Uri("http://www.google.com/"), i);
i = (Uri)o.Annotation(typeof(Uri));
Assert.AreEqual(new Uri("http://www.google.com/"), i);
}
[Test]
public void GetAnnotation_NeverSet()
{
JObject o = new JObject();
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
s = (string)o.Annotation(typeof(string));
Assert.AreEqual(null, s);
}
[Test]
public void GetAnnotations()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation("A string 2!");
o.AddAnnotation("A string 3!");
IList<string> l = o.Annotations<string>().ToList();
Assert.AreEqual(3, l.Count);
Assert.AreEqual("A string!", l[0]);
Assert.AreEqual("A string 2!", l[1]);
Assert.AreEqual("A string 3!", l[2]);
l = o.Annotations(typeof(string)).Cast<string>().ToList();
Assert.AreEqual(3, l.Count);
Assert.AreEqual("A string!", l[0]);
Assert.AreEqual("A string 2!", l[1]);
Assert.AreEqual("A string 3!", l[2]);
}
[Test]
public void GetAnnotations_MultipleTypes()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation("A string 2!");
o.AddAnnotation("A string 3!");
o.AddAnnotation(new Uri("http://www.google.com/"));
IList<object> l = o.Annotations<object>().ToList();
Assert.AreEqual(4, l.Count);
Assert.AreEqual("A string!", l[0]);
Assert.AreEqual("A string 2!", l[1]);
Assert.AreEqual("A string 3!", l[2]);
Assert.AreEqual(new Uri("http://www.google.com/"), l[3]);
l = o.Annotations(typeof(object)).ToList();
Assert.AreEqual(4, l.Count);
Assert.AreEqual("A string!", l[0]);
Assert.AreEqual("A string 2!", l[1]);
Assert.AreEqual("A string 3!", l[2]);
Assert.AreEqual(new Uri("http://www.google.com/"), l[3]);
}
[Test]
public void RemoveAnnotation()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.RemoveAnnotations<string>();
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
}
[Test]
public void RemoveAnnotation_NonGeneric()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.RemoveAnnotations(typeof(string));
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
s = (string)o.Annotation(typeof(string));
Assert.AreEqual(null, s);
}
[Test]
public void RemoveAnnotation_Multiple()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation("A string 2!");
o.AddAnnotation("A string 3!");
o.RemoveAnnotations<string>();
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
o.AddAnnotation("A string 4!");
s = o.Annotation<string>();
Assert.AreEqual("A string 4!", s);
Uri i = (Uri)o.Annotation(typeof(Uri));
Assert.AreEqual(null, i);
}
[Test]
public void RemoveAnnotation_MultipleCalls()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation(new Uri("http://www.google.com/"));
o.RemoveAnnotations<string>();
o.RemoveAnnotations<Uri>();
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
Uri i = o.Annotation<Uri>();
Assert.AreEqual(null, i);
}
[Test]
public void RemoveAnnotation_Multiple_NonGeneric()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation("A string 2!");
o.RemoveAnnotations(typeof(string));
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
}
[Test]
public void RemoveAnnotation_MultipleCalls_NonGeneric()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation(new Uri("http://www.google.com/"));
o.RemoveAnnotations(typeof(string));
o.RemoveAnnotations(typeof(Uri));
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
Uri i = o.Annotation<Uri>();
Assert.AreEqual(null, i);
}
[Test]
public void RemoveAnnotation_MultipleWithDifferentTypes()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation(new Uri("http://www.google.com/"));
o.RemoveAnnotations<string>();
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
Uri i = o.Annotation<Uri>();
Assert.AreEqual(new Uri("http://www.google.com/"), i);
}
[Test]
public void RemoveAnnotation_MultipleWithDifferentTypes_NonGeneric()
{
JObject o = new JObject();
o.AddAnnotation("A string!");
o.AddAnnotation(new Uri("http://www.google.com/"));
o.RemoveAnnotations(typeof(string));
string s = o.Annotation<string>();
Assert.AreEqual(null, s);
Uri i = o.Annotation<Uri>();
Assert.AreEqual(new Uri("http://www.google.com/"), i);
}
}
}
@@ -67,6 +67,7 @@ namespace Newtonsoft.Json.Tests.Linq
counts[s] = c;
}
#if !NETFX_CORE
[Test]
public void DeserializeLargeDynamic()
{
@@ -100,6 +101,7 @@ namespace Newtonsoft.Json.Tests.Linq
Console.WriteLine("Time (secs): " + sw.Elapsed.TotalSeconds);
}
#endif
[Test]
public void JObjectPropertyNames()
@@ -208,8 +208,6 @@ namespace Newtonsoft.Json.Tests.Linq
]
}";
StringReader sr = new StringReader(input);
JObject o = JObject.Parse(input);
using (JTokenReader jsonReader = new JTokenReader(o))
@@ -220,12 +218,14 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(0, lineInfo.LineNumber);
Assert.AreEqual(0, lineInfo.LinePosition);
Assert.AreEqual(false, lineInfo.HasLineInfo());
Assert.AreEqual(null, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject);
Assert.AreEqual(1, lineInfo.LineNumber);
Assert.AreEqual(1, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
@@ -233,6 +233,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(2, lineInfo.LineNumber);
Assert.AreEqual(7, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("CPU"), jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
@@ -240,6 +241,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(2, lineInfo.LineNumber);
Assert.AreEqual(15, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("CPU").Value, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
@@ -247,12 +249,14 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(10, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("Drives"), jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray);
Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(12, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("Drives").Value, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
@@ -260,6 +264,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(4, lineInfo.LineNumber);
Assert.AreEqual(22, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"][0], jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
@@ -267,21 +272,29 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(5, lineInfo.LineNumber);
Assert.AreEqual(30, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"][1], jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray);
Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(12, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"], jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject);
Assert.AreEqual(1, lineInfo.LineNumber);
Assert.AreEqual(1, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.None);
Assert.AreEqual(null, jsonReader.CurrentToken);
jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.None);
Assert.AreEqual(null, jsonReader.CurrentToken);
}
}
@@ -471,15 +484,18 @@ namespace Newtonsoft.Json.Tests.Linq
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
JTokenReader reader = (JTokenReader)o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.AreEqual(o, reader.CurrentToken);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.AreEqual(o.Property("Name"), reader.CurrentToken);
reader.ReadAsInt32();
Assert.AreEqual(o["Name"], reader.CurrentToken);
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
@@ -717,6 +717,27 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(3, (int)descendants[descendants.Count - 1]);
}
[Test]
public void DescendantsAndSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendantsAndSelf = a.DescendantsAndSelf().ToList();
Assert.AreEqual(11, descendantsAndSelf.Count());
Assert.AreEqual(a, descendantsAndSelf[0]);
Assert.AreEqual(5, (int)descendantsAndSelf[1]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 4]));
Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 3]);
Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 2]);
Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 1]);
}
[Test]
public void CreateWriter()
{
@@ -140,6 +140,62 @@ namespace Newtonsoft.Json.Tests.Linq
}
}
[Test]
public void CurrentToken()
{
using (JTokenWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual(null, jsonWriter.CurrentToken);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(jsonWriter.Token, jsonWriter.CurrentToken);
JObject o = (JObject)jsonWriter.Token;
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual(o.Property("CPU"), jsonWriter.CurrentToken);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(o["CPU"], jsonWriter.CurrentToken);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual(o.Property("Drives"), jsonWriter.CurrentToken);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(o["Drives"], jsonWriter.CurrentToken);
JArray a = (JArray)jsonWriter.CurrentToken;
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(a, jsonWriter.CurrentToken);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual(o, jsonWriter.CurrentToken);
}
}
[Test]
public void WriteComment()
{
@@ -213,6 +213,7 @@
<Compile Include="LinqToSql\LinqToSqlClassesSerializationTests.cs" />
<Compile Include="LinqToSql\Person.cs" />
<Compile Include="LinqToSql\Role.cs" />
<Compile Include="Linq\AnnotationsTests.cs" />
<Compile Include="Linq\ComponentModel\BindingTests.cs" />
<Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
<Compile Include="Linq\DynamicTests.cs" />
@@ -240,6 +241,7 @@
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Schema\JsonSchemaSpecTests.cs" />
<Compile Include="Schema\JsonSchemaTests.cs" />
<Compile Include="Schema\PerformanceTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\ConstructorHandlingTests.cs" />
<Compile Include="Serialization\ContractResolverTests.cs" />
@@ -76,4 +76,4 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.6.17929")]
[assembly: AssemblyFileVersion("6.0.7.18022")]
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Schema;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class PerformanceTests : TestFixtureBase
{
[Test]
public void ReaderPerformance()
{
string json = @"[
{
""id"": 2,
""name"": ""An ice sculpture"",
""price"": 12.50,
""tags"": [""cold"", ""ice""],
""dimensions"": {
""length"": 7.0,
""width"": 12.0,
""height"": 9.5
},
""warehouseLocation"": {
""latitude"": -78.75,
""longitude"": 20.4
}
},
{
""id"": 3,
""name"": ""A blue mouse"",
""price"": 25.50,
""dimensions"": {
""length"": 3.1,
""width"": 1.0,
""height"": 1.0
},
""warehouseLocation"": {
""latitude"": 54.4,
""longitude"": -32.7
}
}
]";
JsonSchema schema = JsonSchema.Parse(@"{
""$schema"": ""http://json-schema.org/draft-04/schema#"",
""title"": ""Product set"",
""type"": ""array"",
""items"": {
""title"": ""Product"",
""type"": ""object"",
""properties"": {
""id"": {
""description"": ""The unique identifier for a product"",
""type"": ""number"",
""required"": true
},
""name"": {
""type"": ""string"",
""required"": true
},
""price"": {
""type"": ""number"",
""minimum"": 0,
""exclusiveMinimum"": true,
""required"": true
},
""tags"": {
""type"": ""array"",
""items"": {
""type"": ""string""
},
""minItems"": 1,
""uniqueItems"": true
},
""dimensions"": {
""type"": ""object"",
""properties"": {
""length"": {""type"": ""number"",""required"": true},
""width"": {""type"": ""number"",""required"": true},
""height"": {""type"": ""number"",""required"": true}
}
},
""warehouseLocation"": {
""description"": ""A geographical coordinate"",
""type"": ""object"",
""properties"": {
""latitude"": { ""type"": ""number"" },
""longitude"": { ""type"": ""number"" }
}
}
}
}
}");
using (var tester = new PerformanceTester("Reader"))
{
for (int i = 0; i < 5000; i++)
{
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
validatingReader.Schema = schema;
while (validatingReader.Read())
{
}
}
}
}
}
public class PerformanceTester : IDisposable
{
private readonly Stopwatch _stopwatch = new Stopwatch();
private readonly Action<TimeSpan> _callback;
public PerformanceTester(string description)
: this(ts => Console.WriteLine(description + ": " + ts.TotalSeconds))
{
}
public PerformanceTester(Action<TimeSpan> callback)
{
_callback = callback;
_stopwatch.Start();
}
public static PerformanceTester Start(Action<TimeSpan> callback)
{
return new PerformanceTester(callback);
}
public void Dispose()
{
_stopwatch.Stop();
if (_callback != null)
_callback(Result);
}
public TimeSpan Result
{
get { return _stopwatch.Elapsed; }
}
}
}
@@ -368,6 +368,20 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("fff", obj.Field1);
}
#endif
[Test]
public void PopulateTest()
{
var test = JsonConvert.DeserializeObject<PopulateWithNullJsonTest>("{\"IntValue\":null}");
Console.WriteLine("IntValue:{0}", test.IntValue);
}
public class PopulateWithNullJsonTest
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, NullValueHandling = NullValueHandling.Ignore)]
[DefaultValue(6)]
public int IntValue { get; set; }
}
}
#if !NET20
@@ -8374,6 +8374,46 @@ Path '', line 1, position 1.");
}
#endif
[Test]
public void ParameterizedConstructorWithBasePrivateProperties()
{
var original = new DerivedConstructorType("Base", "Derived");
var serializerSettings = new JsonSerializerSettings();
var jsonCopy = JsonConvert.SerializeObject(original, serializerSettings);
Console.WriteLine(original);
var clonedObject = JsonConvert.DeserializeObject<DerivedConstructorType>(jsonCopy, serializerSettings);
Assert.AreEqual("Base", clonedObject.BaseProperty);
Assert.AreEqual("Derived", clonedObject.DerivedProperty);
}
public class DerivedConstructorType : BaseConstructorType
{
public DerivedConstructorType(string baseProperty, string derivedProperty)
: base(baseProperty)
{
DerivedProperty = derivedProperty;
}
[JsonProperty]
public string DerivedProperty { get; private set; }
}
public class BaseConstructorType
{
[JsonProperty]
public string BaseProperty { get; private set; }
public BaseConstructorType(string baseProperty)
{
BaseProperty = baseProperty;
}
}
public class ErroringJsonConverter : JsonConverter
{
public ErroringJsonConverter(string s)
@@ -23,6 +23,11 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
#if !(PORTABLE || PORTABLE40)
using System.Collections.ObjectModel;
#if !(NET35 || NET20)
@@ -1836,6 +1841,55 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(1UL, item.WantedUnitID);
}
#endif
#if !(NET20 || NET35)
[Test]
public void GenericItemTypeCollection()
{
DataType data = new DataType();
data.Rows.Add("key", new List<MyInterfaceImplementationType> { new MyInterfaceImplementationType() { SomeProperty = "property" } });
string serialized = JsonConvert.SerializeObject(data, Formatting.Indented);
StringAssert.AreEqual(@"{
""Rows"": {
""key"": {
""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.MyInterfaceImplementationType, Newtonsoft.Json.Tests]], mscorlib"",
""$values"": [
{
""SomeProperty"": ""property""
}
]
}
}
}", serialized);
DataType deserialized = JsonConvert.DeserializeObject<DataType>(serialized);
Assert.AreEqual("property", deserialized.Rows["key"].First().SomeProperty);
}
#endif
}
public class DataType
{
public DataType()
{
Rows = new Dictionary<string, IEnumerable<IMyInterfaceType>>();
}
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto, TypeNameHandling = TypeNameHandling.Auto)]
public Dictionary<string, IEnumerable<IMyInterfaceType>> Rows { get; private set; }
}
public interface IMyInterfaceType
{
string SomeProperty { get; set; }
}
public class MyInterfaceImplementationType : IMyInterfaceType
{
public string SomeProperty { get; set; }
}
#if !(NETFX_CORE || ASPNETCORE50)
+5 -2
View File
@@ -261,11 +261,14 @@ namespace Newtonsoft.Json.Tests
protected void TestSetup()
#endif
{
//#if !NETFX_CORE
#if !NETFX_CORE
// CultureInfo turkey = CultureInfo.CreateSpecificCulture("tr");
// Thread.CurrentThread.CurrentCulture = turkey;
// Thread.CurrentThread.CurrentUICulture = turkey;
//#endif
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
#endif
JsonConvert.DefaultSettings = null;
}
+10 -10
View File
@@ -35,7 +35,7 @@ using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
public class BsonReader : JsonReader
{
@@ -61,15 +61,15 @@ namespace Newtonsoft.Json.Bson
private enum BsonReaderState
{
Normal,
ReferenceStart,
ReferenceRef,
ReferenceId,
CodeWScopeStart,
CodeWScopeCode,
CodeWScopeScope,
CodeWScopeScopeObject,
CodeWScopeScopeEnd
Normal = 0,
ReferenceStart = 1,
ReferenceRef = 2,
ReferenceId = 3,
CodeWScopeStart = 4,
CodeWScopeCode = 5,
CodeWScopeScope = 6,
CodeWScopeScopeObject = 7,
CodeWScopeScopeEnd = 8
}
private class ContainerContext
@@ -79,7 +79,7 @@ namespace Newtonsoft.Json.Converters
case JsonToken.StartArray:
return ReadList(reader);
default:
if (JsonReader.IsPrimitiveToken(reader.TokenType))
if (JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
return reader.Value;
throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
+3 -3
View File
@@ -33,17 +33,17 @@ namespace Newtonsoft.Json
/// <summary>
/// Date formatted strings are not parsed to a date type and are read as strings.
/// </summary>
None,
None = 0,
/// <summary>
/// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to <see cref="DateTime"/>.
/// </summary>
DateTime,
DateTime = 1,
#if !NET20
/// <summary>
/// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to <see cref="DateTimeOffset"/>.
/// </summary>
DateTimeOffset
DateTimeOffset = 2
#endif
}
}
+4 -4
View File
@@ -35,22 +35,22 @@ namespace Newtonsoft.Json
/// <summary>
/// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time.
/// </summary>
Local,
Local = 0,
/// <summary>
/// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC.
/// </summary>
Utc,
Utc = 1,
/// <summary>
/// Treat as a local time if a <see cref="DateTime"/> is being converted to a string.
/// If a string is being converted to <see cref="DateTime"/>, convert to a local time if a time zone is specified.
/// </summary>
Unspecified,
Unspecified = 2,
/// <summary>
/// Time zone information should be preserved when converting.
/// </summary>
RoundtripKind
RoundtripKind = 3
}
}
+3 -3
View File
@@ -34,17 +34,17 @@ namespace Newtonsoft.Json
/// <summary>
/// Write special floating point values as strings in JSON, e.g. "NaN", "Infinity", "-Infinity".
/// </summary>
String,
String = 0,
/// <summary>
/// Write special floating point values as symbols in JSON, e.g. NaN, Infinity, -Infinity.
/// Note that this will produce non-valid JSON.
/// </summary>
Symbol,
Symbol = 1,
/// <summary>
/// Write special floating point values as the property's default value in JSON, e.g. 0.0 for a <see cref="System.Double"/> property, null for a <see cref="System.Nullable{Double}"/> property.
/// </summary>
DefaultValue
DefaultValue = 2
}
}
+2 -2
View File
@@ -33,11 +33,11 @@ namespace Newtonsoft.Json
/// <summary>
/// Floating point numbers are parsed to <see cref="Double"/>.
/// </summary>
Double,
Double = 0,
/// <summary>
/// Floating point numbers are parsed to <see cref="Decimal"/>.
/// </summary>
Decimal
Decimal = 1
}
}
@@ -11,12 +11,12 @@ namespace System.Runtime.Serialization.Formatters
/// <summary>
/// In simple mode, the assembly used during deserialization need not match exactly the assembly used during serialization. Specifically, the version numbers need not match as the LoadWithPartialName method is used to load the assembly.
/// </summary>
Simple,
Simple = 0,
/// <summary>
/// In full mode, the assembly used during deserialization must match exactly the assembly used during serialization. The Load method of the Assembly class is used to load the assembly.
/// </summary>
Full
Full = 1
}
}
+2 -2
View File
@@ -33,11 +33,11 @@ namespace Newtonsoft.Json
/// <summary>
/// No special formatting is applied. This is the default.
/// </summary>
None,
None = 0,
/// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary>
Indented
Indented = 1
}
}
+4 -4
View File
@@ -33,10 +33,10 @@ namespace Newtonsoft.Json
{
internal enum JsonContainerType
{
None,
Object,
Array,
Constructor
None = 0,
Object = 1,
Array = 2,
Constructor = 3
}
internal struct JsonPosition
+4 -35
View File
@@ -39,7 +39,7 @@ using System.Linq;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
public abstract class JsonReader : IDisposable
{
@@ -251,7 +251,7 @@ namespace Newtonsoft.Json
get
{
int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth;
else
return depth + 1;
@@ -712,7 +712,7 @@ namespace Newtonsoft.Json
if (t == JsonToken.Null)
return null;
if (IsPrimitiveToken(t))
if (JsonTokenUtils.IsPrimitiveToken(t))
{
if (Value != null)
{
@@ -823,7 +823,7 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.PropertyName)
Read();
if (IsStartToken(TokenType))
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
@@ -963,37 +963,6 @@ namespace Newtonsoft.Json
_currentState = State.Finished;
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
+1 -1
View File
@@ -37,7 +37,7 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public class JsonTextWriter : JsonWriter
{
+18 -18
View File
@@ -37,91 +37,91 @@ namespace Newtonsoft.Json
/// <summary>
/// This is returned by the <see cref="JsonReader"/> if a <see cref="JsonReader.Read"/> method has not been called.
/// </summary>
None,
None = 0,
/// <summary>
/// An object start token.
/// </summary>
StartObject,
StartObject = 1,
/// <summary>
/// An array start token.
/// </summary>
StartArray,
StartArray = 2,
/// <summary>
/// A constructor start token.
/// </summary>
StartConstructor,
StartConstructor = 3,
/// <summary>
/// An object property name.
/// </summary>
PropertyName,
PropertyName = 4,
/// <summary>
/// A comment.
/// </summary>
Comment,
Comment = 5,
/// <summary>
/// Raw JSON.
/// </summary>
Raw,
Raw = 6,
/// <summary>
/// An integer.
/// </summary>
Integer,
Integer = 7,
/// <summary>
/// A float.
/// </summary>
Float,
Float = 8,
/// <summary>
/// A string.
/// </summary>
String,
String = 9,
/// <summary>
/// A boolean.
/// </summary>
Boolean,
Boolean = 10,
/// <summary>
/// A null token.
/// </summary>
Null,
Null = 11,
/// <summary>
/// An undefined token.
/// </summary>
Undefined,
Undefined = 12,
/// <summary>
/// An object end token.
/// </summary>
EndObject,
EndObject = 13,
/// <summary>
/// An array end token.
/// </summary>
EndArray,
EndArray = 14,
/// <summary>
/// A constructor end token.
/// </summary>
EndConstructor,
EndConstructor = 15,
/// <summary>
/// A Date.
/// </summary>
Date,
Date = 16,
/// <summary>
/// Byte data.
/// </summary>
Bytes
Bytes = 17
}
}
+2 -2
View File
@@ -461,7 +461,7 @@ namespace Newtonsoft.Json
JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder();
_model = builder.Build(_schema);
if (!JsonWriter.IsStartToken(_reader.TokenType))
if (!JsonTokenUtils.IsStartToken(_reader.TokenType))
Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas));
}
@@ -578,7 +578,7 @@ namespace Newtonsoft.Json
{
if (schemaScope.CurrentItemWriter == null)
{
if (JsonWriter.IsEndToken(_reader.TokenType))
if (JsonTokenUtils.IsEndToken(_reader.TokenType))
continue;
schemaScope.CurrentItemWriter = new JTokenWriter();
+135 -129
View File
@@ -41,22 +41,22 @@ using System.Linq;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
internal enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Closed,
Error
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
@@ -449,13 +449,35 @@ namespace Newtonsoft.Json
WriteToken(reader, writeChildren, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// A null value can be passed to the method for token's that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.</param>
public void WriteToken(JsonToken token, object value)
{
WriteTokenInternal(token, value);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteTokenInternal(token, null);
}
internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate)
{
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
else if (!JsonTokenUtils.IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
@@ -467,103 +489,113 @@ namespace Newtonsoft.Json
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && string.Equals(constructorName, "Date", StringComparison.Ordinal))
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment((reader.Value != null) ? reader.Value.ToString() : null);
break;
case JsonToken.Integer:
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (reader.Value is BigInteger)
{
WriteValue((BigInteger)reader.Value);
}
else
#endif
{
WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
object value = reader.Value;
if (value is decimal)
WriteValue((decimal)value);
else if (value is double)
WriteValue((double)value);
else if (value is float)
WriteValue((float)value);
else
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
#if !NET20
if (reader.Value is DateTimeOffset)
WriteValue((DateTimeOffset)reader.Value);
else
#endif
WriteValue(Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Raw:
WriteRawValue((reader.Value != null) ? reader.Value.ToString() : null);
break;
case JsonToken.Bytes:
if (reader.Value is Guid)
WriteValue((Guid)reader.Value);
else
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
WriteConstructorDate(reader);
else
WriteTokenInternal(reader.TokenType, reader.Value);
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
private void WriteTokenInternal(JsonToken tokenType, object value)
{
switch (tokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, "value");
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, "value");
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment((value != null) ? value.ToString() : null);
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, "value");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (value is BigInteger)
{
WriteValue((BigInteger)value);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, "value");
if (value is decimal)
WriteValue((decimal)value);
else if (value is double)
WriteValue((double)value);
else if (value is float)
WriteValue((float)value);
else
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, "value");
WriteValue(value.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, "value");
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, "value");
#if !NET20
if (value is DateTimeOffset)
WriteValue((DateTimeOffset)value);
else
#endif
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Raw:
WriteRawValue((value != null) ? value.ToString() : null);
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, "value");
if (value is Guid)
WriteValue((Guid)value);
else
WriteValue((byte[])value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", tokenType, "Unexpected token type.");
}
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
@@ -582,32 +614,6 @@ namespace Newtonsoft.Json
WriteValue(date);
}
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
+17
View File
@@ -272,6 +272,23 @@ namespace Newtonsoft.Json.Linq
/// <returns>An <see cref="IEnumerable{JToken}"/> containing the descendant tokens of the <see cref="JToken"/>.</returns>
public IEnumerable<JToken> Descendants()
{
return GetDescendants(false);
}
/// <summary>
/// Returns a collection of the tokens that contain this token, and all descendant tokens of this token, in document order.
/// </summary>
/// <returns>An <see cref="IEnumerable{JToken}"/> containing this token, and all the descendant tokens of the <see cref="JToken"/>.</returns>
public IEnumerable<JToken> DescendantsAndSelf()
{
return GetDescendants(true);
}
internal IEnumerable<JToken> GetDescendants(bool self)
{
if (self)
yield return this;
foreach (JToken o in ChildrenTokens)
{
yield return o;
+296 -8
View File
@@ -59,13 +59,15 @@ namespace Newtonsoft.Json.Linq
, IDynamicMetaObjectProvider
#endif
{
private static JTokenEqualityComparer _equalityComparer;
private JContainer _parent;
private JToken _previous;
private JToken _next;
private static JTokenEqualityComparer _equalityComparer;
private object _annotations;
private int? _lineNumber;
private int? _linePosition;
//private int? _lineNumber;
//private int? _linePosition;
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 };
@@ -1923,25 +1925,50 @@ namespace Newtonsoft.Json.Linq
SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition);
}
private class LineInfoAnnotation
{
internal readonly int LineNumber;
internal readonly int LinePosition;
public LineInfoAnnotation(int lineNumber, int linePosition)
{
LineNumber = lineNumber;
LinePosition = linePosition;
}
}
internal void SetLineInfo(int lineNumber, int linePosition)
{
_lineNumber = lineNumber;
_linePosition = linePosition;
AddAnnotation(new LineInfoAnnotation(lineNumber, linePosition));
}
bool IJsonLineInfo.HasLineInfo()
{
return (_lineNumber != null && _linePosition != null);
return (Annotation<LineInfoAnnotation>() != null);
}
int IJsonLineInfo.LineNumber
{
get { return _lineNumber ?? 0; }
get
{
LineInfoAnnotation annotation = Annotation<LineInfoAnnotation>();
if (annotation != null)
return annotation.LineNumber;
return 0;
}
}
int IJsonLineInfo.LinePosition
{
get { return _linePosition ?? 0; }
get
{
LineInfoAnnotation annotation = Annotation<LineInfoAnnotation>();
if (annotation != null)
return annotation.LinePosition;
return 0;
}
}
/// <summary>
@@ -2047,5 +2074,266 @@ namespace Newtonsoft.Json.Linq
{
return CloneToken();
}
/// <summary>
/// Adds an object to the annotation list of this <see cref="JToken"/>.
/// </summary>
/// <param name="annotation">The annotation to add.</param>
public void AddAnnotation(object annotation)
{
if (annotation == null)
throw new ArgumentNullException("annotation");
if (_annotations == null)
{
_annotations = (annotation is object[]) ? new [] { annotation } : annotation;
}
else
{
object[] annotations = _annotations as object[];
if (annotations == null)
{
_annotations = new [] { _annotations, annotation };
}
else
{
int index = 0;
while (index < annotations.Length && annotations[index] != null)
{
index++;
}
if (index == annotations.Length)
{
Array.Resize(ref annotations, index * 2);
_annotations = annotations;
}
annotations[index] = annotation;
}
}
}
/// <summary>
/// Get the first annotation object of the specified type from this <see cref="JToken"/>.
/// </summary>
/// <typeparam name="T">The type of the annotation to retrieve.</typeparam>
/// <returns>The first annotation object that matches the specified type, or <c>null</c> if no annotation is of the specified type.</returns>
public T Annotation<T>() where T : class
{
if (_annotations != null)
{
object[] annotations = _annotations as object[];
if (annotations == null)
{
return (_annotations as T);
}
for (int i = 0; i < annotations.Length; i++)
{
object annotation = annotations[i];
if (annotation == null)
break;
T local = annotation as T;
if (local != null)
return local;
}
}
return default(T);
}
/// <summary>
/// Gets the first annotation object of the specified type from this <see cref="JToken"/>.
/// </summary>
/// <param name="type">The <see cref="Type"/> of the annotation to retrieve.</param>
/// <returns>The first annotation object that matches the specified type, or <c>null</c> if no annotation is of the specified type.</returns>
public object Annotation(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (_annotations != null)
{
object[] annotations = _annotations as object[];
if (annotations == null)
{
if (type.IsInstanceOfType(_annotations))
return _annotations;
}
else
{
for (int i = 0; i < annotations.Length; i++)
{
object o = annotations[i];
if (o == null)
break;
if (type.IsInstanceOfType(o))
return o;
}
}
}
return null;
}
/// <summary>
/// Gets a collection of annotations of the specified type for this <see cref="JToken"/>.
/// </summary>
/// <typeparam name="T">The type of the annotations to retrieve.</typeparam>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the annotations for this <see cref="JToken"/>.</returns>
public IEnumerable<T> Annotations<T>() where T : class
{
if (_annotations == null)
yield break;
object[] annotations = _annotations as object[];
if (annotations != null)
{
for (int i = 0; i < annotations.Length; i++)
{
object o = annotations[i];
if (o == null)
break;
T casted = o as T;
if (casted != null)
yield return casted;
}
yield break;
}
T annotation = _annotations as T;
if (annotation == null)
yield break;
yield return annotation;
}
/// <summary>
/// Gets a collection of annotations of the specified type for this <see cref="JToken"/>.
/// </summary>
/// <param name="type">The <see cref="Type"/> of the annotations to retrieve.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="Object"/> that contains the annotations that match the specified type for this <see cref="JToken"/>.</returns>
public IEnumerable<object> Annotations(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (_annotations == null)
yield break;
object[] annotations = _annotations as object[];
if (annotations != null)
{
for (int i = 0; i < annotations.Length; i++)
{
object o = annotations[i];
if (o == null)
break;
if (type.IsInstanceOfType(o))
yield return o;
}
yield break;
}
if (!type.IsInstanceOfType(_annotations))
yield break;
yield return _annotations;
}
/// <summary>
/// Removes the annotations of the specified type from this <see cref="JToken"/>.
/// </summary>
/// <typeparam name="T">The type of annotations to remove.</typeparam>
public void RemoveAnnotations<T>() where T : class
{
if (_annotations != null)
{
object[] annotations = _annotations as object[];
if (annotations == null)
{
if (_annotations is T)
_annotations = null;
}
else
{
int index = 0;
int keepCount = 0;
while (index < annotations.Length)
{
object obj2 = annotations[index];
if (obj2 == null)
break;
if (!(obj2 is T))
annotations[keepCount++] = obj2;
index++;
}
if (keepCount != 0)
{
while (keepCount < index)
{
annotations[keepCount++] = null;
}
}
else
{
_annotations = null;
}
}
}
}
/// <summary>
/// Removes the annotations of the specified type from this <see cref="JToken"/>.
/// </summary>
/// <param name="type">The <see cref="Type"/> of annotations to remove.</param>
public void RemoveAnnotations(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (_annotations != null)
{
object[] annotations = _annotations as object[];
if (annotations == null)
{
if (type.IsInstanceOfType(_annotations))
_annotations = null;
}
else
{
int index = 0;
int keepCount = 0;
while (index < annotations.Length)
{
object o = annotations[index];
if (o == null)
break;
if (!type.IsInstanceOfType(o))
annotations[keepCount++] = o;
index++;
}
if (keepCount != 0)
{
while (keepCount < index)
{
annotations[keepCount++] = null;
}
}
else
{
_annotations = null;
}
}
}
}
}
}
+15 -3
View File
@@ -29,14 +29,22 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
public class JTokenReader : JsonReader, IJsonLineInfo
{
private readonly string _initialPath;
private readonly JToken _root;
private JToken _parent;
internal JToken _current;
private JToken _current;
/// <summary>
/// Gets the <see cref="JToken"/> at the reader's current position.
/// </summary>
public JToken CurrentToken
{
get { return _current; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JTokenReader"/> class.
@@ -47,7 +55,6 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(token, "token");
_root = token;
_current = token;
}
internal JTokenReader(JToken token, string initialPath)
@@ -118,6 +125,9 @@ namespace Newtonsoft.Json.Linq
{
if (CurrentState != State.Start)
{
if (_current == null)
return false;
JContainer container = _current as JContainer;
if (container != null && _parent != container)
return ReadInto(container);
@@ -125,6 +135,7 @@ namespace Newtonsoft.Json.Linq
return ReadOver(_current);
}
_current = _root;
SetToken(_current);
return true;
}
@@ -165,6 +176,7 @@ namespace Newtonsoft.Json.Linq
private bool ReadToEnd()
{
_current = null;
SetToken(JsonToken.None);
return false;
}
+18 -18
View File
@@ -33,91 +33,91 @@ namespace Newtonsoft.Json.Linq
/// <summary>
/// No token type has been set.
/// </summary>
None,
None = 0,
/// <summary>
/// A JSON object.
/// </summary>
Object,
Object = 1,
/// <summary>
/// A JSON array.
/// </summary>
Array,
Array = 2,
/// <summary>
/// A JSON constructor.
/// </summary>
Constructor,
Constructor = 3,
/// <summary>
/// A JSON object property.
/// </summary>
Property,
Property = 4,
/// <summary>
/// A comment.
/// </summary>
Comment,
Comment = 5,
/// <summary>
/// An integer value.
/// </summary>
Integer,
Integer = 6,
/// <summary>
/// A float value.
/// </summary>
Float,
Float = 7,
/// <summary>
/// A string value.
/// </summary>
String,
String = 8,
/// <summary>
/// A boolean value.
/// </summary>
Boolean,
Boolean = 9,
/// <summary>
/// A null value.
/// </summary>
Null,
Null = 10,
/// <summary>
/// An undefined value.
/// </summary>
Undefined,
Undefined = 11,
/// <summary>
/// A date value.
/// </summary>
Date,
Date = 12,
/// <summary>
/// A raw JSON value.
/// </summary>
Raw,
Raw = 13,
/// <summary>
/// A collection of bytes value.
/// </summary>
Bytes,
Bytes = 14,
/// <summary>
/// A Guid value.
/// </summary>
Guid,
Guid = 15,
/// <summary>
/// A Uri value.
/// </summary>
Uri,
Uri = 16,
/// <summary>
/// A TimeSpan value.
/// </summary>
TimeSpan
TimeSpan = 17
}
}
+14 -1
View File
@@ -33,7 +33,7 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public class JTokenWriter : JsonWriter
{
@@ -41,6 +41,15 @@ namespace Newtonsoft.Json.Linq
private JContainer _parent;
// used when writer is writing single value and the value has no containing parent
private JValue _value;
private JToken _current;
/// <summary>
/// Gets the <see cref="JToken"/> at the writer's current position.
/// </summary>
public JToken CurrentToken
{
get { return _current; }
}
/// <summary>
/// Gets the token being writen.
@@ -109,10 +118,12 @@ namespace Newtonsoft.Json.Linq
_parent.AddAndSkipParentCheck(container);
_parent = container;
_current = container;
}
private void RemoveParent()
{
_current = _parent;
_parent = _parent.Parent;
if (_parent != null && _parent.Type == JTokenType.Property)
@@ -172,6 +183,7 @@ namespace Newtonsoft.Json.Linq
if (_parent != null)
{
_parent.Add(value);
_current = _parent.Last;
if (_parent.Type == JTokenType.Property)
_parent = _parent.Parent;
@@ -179,6 +191,7 @@ namespace Newtonsoft.Json.Linq
else
{
_value = value ?? JValue.CreateNull();
_current = _value;
}
}
@@ -5,16 +5,16 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal enum QueryOperator
{
None,
Equals,
NotEquals,
Exists,
LessThan,
LessThanOrEquals,
GreaterThan,
GreaterThanOrEquals,
And,
Or
None = 0,
Equals = 1,
NotEquals = 2,
Exists = 3,
LessThan = 4,
LessThanOrEquals = 5,
GreaterThan = 6,
GreaterThanOrEquals = 7,
And = 8,
Or = 9
}
internal abstract class QueryExpression
@@ -6,15 +6,15 @@ namespace Newtonsoft.Json.Linq
public enum MergeArrayHandling
{
/// <summary>Concatenate arrays.</summary>
Concat,
Concat = 0,
/// <summary>Union arrays, skipping items that already exist.</summary>
Union,
Union = 1,
/// <summary>Replace all array items.</summary>
Replace,
Replace = 2,
/// <summary>Merge array items together, matched by index.</summary>
Merge
Merge = 3
}
}
+3 -3
View File
@@ -39,20 +39,20 @@ namespace Newtonsoft.Json
/// All public members are serialized by default. Members can be excluded using <see cref="JsonIgnoreAttribute"/> or <see cref="NonSerializedAttribute"/>.
/// This is the default member serialization mode.
/// </summary>
OptOut,
OptOut = 0,
/// <summary>
/// Only members must be marked with <see cref="JsonPropertyAttribute"/> or <see cref="DataMemberAttribute"/> are serialized.
/// This member serialization mode can also be set by marking the class with <see cref="DataContractAttribute"/>.
/// </summary>
OptIn,
OptIn = 1,
/// <summary>
/// All public and private fields are serialized. Members can be excluded using <see cref="JsonIgnoreAttribute"/> or <see cref="NonSerializedAttribute"/>.
/// This member serialization mode can also be set by marking the class with <see cref="SerializableAttribute"/>
/// and setting IgnoreSerializableAttribute on <see cref="DefaultContractResolver"/> to false.
/// </summary>
Fields
Fields = 2
#pragma warning restore 1584,1711,1572,1581,1580,1574
}
}
@@ -136,6 +136,7 @@
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Linq\JPropertyDescriptor.cs" />
<Compile Include="Linq\JRaw.cs" />
@@ -244,6 +244,7 @@
<Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
@@ -244,6 +244,7 @@
<Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
@@ -216,6 +216,7 @@
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\MathUtils.cs" />
@@ -220,6 +220,7 @@
<Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\MathUtils.cs" />
@@ -213,6 +213,7 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
@@ -53,9 +53,10 @@ using System.Security;
#endif
#if !SIGNED
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")]
#else
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
#endif
@@ -91,5 +92,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.6.17929")]
[assembly: AssemblyFileVersion("6.0.7.18022")]
[assembly: CLSCompliant(true)]
+3 -3
View File
@@ -33,16 +33,16 @@ namespace Newtonsoft.Json
/// <summary>
/// The property is not required. The default state.
/// </summary>
Default,
Default = 0,
/// <summary>
/// The property must be defined in JSON but can be a null value.
/// </summary>
AllowNull,
AllowNull = 1,
/// <summary>
/// The property must be defined in JSON and cannot be a null value.
/// </summary>
Always
Always = 2
}
}
@@ -35,19 +35,15 @@ namespace Newtonsoft.Json.Serialization
{
internal enum JsonContractType
{
None,
Object,
Array,
Primitive,
String,
Dictionary,
#if !(NET35 || NET20 || PORTABLE40)
Dynamic,
#endif
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
Serializable,
#endif
Linq
None = 0,
Object = 1,
Array = 2,
Primitive = 3,
String = 4,
Dictionary = 5,
Dynamic = 6,
Serializable = 7,
Linq = 8
}
/// <summary>
@@ -52,9 +52,9 @@ namespace Newtonsoft.Json.Serialization
{
internal enum PropertyPresence
{
None,
Null,
Value
None = 0,
Null = 1,
Value = 2
}
private JsonSerializerProxy _internalSerializer;
@@ -526,7 +526,7 @@ namespace Newtonsoft.Json.Serialization
if (reader.TokenType == JsonToken.StartObject)
{
JObject current = (JObject)reader._current;
JObject current = (JObject)reader.CurrentToken;
JToken refToken = current[JsonTypeReflector.RefPropertyName];
if (refToken != null)
@@ -967,7 +967,7 @@ namespace Newtonsoft.Json.Serialization
// test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)
&& JsonReader.IsPrimitiveToken(tokenType)
&& JsonTokenUtils.IsPrimitiveToken(tokenType)
&& MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue()))
return true;
@@ -1563,7 +1563,7 @@ namespace Newtonsoft.Json.Serialization
}
else
{
Type t = (JsonReader.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider);
Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider);
JsonContract dynamicMemberContract = GetContractSafe(t);
JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member);
+3 -3
View File
@@ -33,16 +33,16 @@ namespace Newtonsoft.Json
/// <summary>
/// Only control characters (e.g. newline) are escaped.
/// </summary>
Default,
Default = 0,
/// <summary>
/// All non-ASCII and control characters (e.g. newline) are escaped.
/// </summary>
EscapeNonAscii,
EscapeNonAscii = 1,
/// <summary>
/// HTML (&lt;, &gt;, &amp;, &apos;, &quot;) and control characters (e.g. newline) are escaped.
/// </summary>
EscapeHtml
EscapeHtml = 2
}
}
+5 -5
View File
@@ -12,27 +12,27 @@ namespace Newtonsoft.Json
/// <summary>
/// Output no tracing and debugging messages.
/// </summary>
Off,
Off = 0,
/// <summary>
/// Output error-handling messages.
/// </summary>
Error,
Error = 1,
/// <summary>
/// Output warnings and error-handling messages.
/// </summary>
Warning,
Warning = 2,
/// <summary>
/// Output informational messages, warnings, and error-handling messages.
/// </summary>
Info,
Info = 3,
/// <summary>
/// Output all debugging and tracing messages.
/// </summary>
Verbose
Verbose = 4
}
}
+50 -54
View File
@@ -46,52 +46,48 @@ namespace Newtonsoft.Json.Utilities
{
internal enum PrimitiveTypeCode
{
Empty,
Object,
Char,
CharNullable,
Boolean,
BooleanNullable,
SByte,
SByteNullable,
Int16,
Int16Nullable,
UInt16,
UInt16Nullable,
Int32,
Int32Nullable,
Byte,
ByteNullable,
UInt32,
UInt32Nullable,
Int64,
Int64Nullable,
UInt64,
UInt64Nullable,
Single,
SingleNullable,
Double,
DoubleNullable,
DateTime,
DateTimeNullable,
#if !NET20
DateTimeOffset,
DateTimeOffsetNullable,
#endif
Decimal,
DecimalNullable,
Guid,
GuidNullable,
TimeSpan,
TimeSpanNullable,
#if !(PORTABLE || NET35 || NET20)
BigInteger,
BigIntegerNullable,
#endif
Uri,
String,
Bytes,
DBNull
Empty = 0,
Object = 1,
Char = 2,
CharNullable = 3,
Boolean = 4,
BooleanNullable = 5,
SByte = 6,
SByteNullable = 7,
Int16 = 8,
Int16Nullable = 9,
UInt16 = 10,
UInt16Nullable = 11,
Int32 = 12,
Int32Nullable = 13,
Byte = 14,
ByteNullable = 15,
UInt32 = 16,
UInt32Nullable = 17,
Int64 = 18,
Int64Nullable = 19,
UInt64 = 20,
UInt64Nullable = 21,
Single = 22,
SingleNullable = 23,
Double = 24,
DoubleNullable = 25,
DateTime = 26,
DateTimeNullable = 27,
DateTimeOffset = 28,
DateTimeOffsetNullable = 29,
Decimal = 30,
DecimalNullable = 31,
Guid = 32,
GuidNullable = 33,
TimeSpan = 34,
TimeSpanNullable = 35,
BigInteger = 36,
BigIntegerNullable = 37,
Uri = 38,
String = 39,
Bytes = 40,
DBNull = 41
}
internal class TypeInformation
@@ -102,10 +98,10 @@ namespace Newtonsoft.Json.Utilities
internal enum ParseResult
{
None,
Success,
Overflow,
Invalid
None = 0,
Success = 1,
Overflow = 2,
Invalid = 3
}
internal static class ConvertUtils
@@ -360,10 +356,10 @@ namespace Newtonsoft.Json.Utilities
#region TryConvert
internal enum ConvertResult
{
Success,
CannotConvertNull,
NotInstantiableType,
NoValidConversion
Success = 0,
CannotConvertNull = 1,
NotInstantiableType = 2,
NoValidConversion = 3
}
public static object Convert(object initialValue, CultureInfo culture, Type targetType)
@@ -29,10 +29,10 @@ namespace Newtonsoft.Json.Utilities
{
internal enum ParserTimeZone
{
Unspecified,
Utc,
LocalWestOfUtc,
LocalEastOfUtc
Unspecified = 0,
Utc = 1,
LocalWestOfUtc = 2,
LocalEastOfUtc = 3
}
internal struct DateTimeParser
@@ -0,0 +1,77 @@
#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.Text;
namespace Newtonsoft.Json.Utilities
{
internal static class JsonTokenUtils
{
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
}
}
@@ -46,11 +46,11 @@ namespace Newtonsoft.Json.Utilities
#if (NETFX_CORE || PORTABLE || PORTABLE40)
internal enum MemberTypes
{
Property,
Field,
Event,
Method,
Other
Property = 0,
Field = 1,
Event = 2,
Method = 3,
Other = 4
}
#endif
@@ -76,6 +76,14 @@ namespace Newtonsoft.Json.Utilities
{
return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo());
}
public static bool IsInstanceOfType(this Type type, object o)
{
if (o == null)
return false;
return IsAssignableFrom(type, o.GetType());
}
#endif
public static MethodInfo Method(this Delegate d)
+7 -7
View File
@@ -37,36 +37,36 @@ namespace Newtonsoft.Json
/// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state.
/// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown.
/// </summary>
Error,
Error = 0,
/// <summary>
/// The <see cref="JsonWriter.Close"/> method has been called.
/// </summary>
Closed,
Closed = 1,
/// <summary>
/// An object is being written.
/// </summary>
Object,
Object = 2,
/// <summary>
/// A array is being written.
/// </summary>
Array,
Array = 3,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
Constructor = 4,
/// <summary>
/// A property is being written.
/// </summary>
Property,
Property = 5,
/// <summary>
/// A write method has not been called.
/// </summary>
Start
Start = 6
}
}
+823 -1171
View File
File diff suppressed because it is too large Load Diff