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/ [Bb]in/
[Oo]bj/ [Oo]bj/
[Ww]orking/ [Ww]orking*/
Build/runbuild.txt Build/runbuild.txt
Doc/doc.shfbproj_* Doc/doc.shfbproj_*
TestResults/ TestResults/
+1 -1
View File
@@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata> <metadata>
<id>Newtonsoft.Json</id> <id>Newtonsoft.Json</id>
<version>6.0.6</version> <version>6.0.7</version>
<title>Json.NET</title> <title>Json.NET</title>
<description>Json.NET is a popular high-performance JSON framework for .NET</description> <description>Json.NET is a popular high-performance JSON framework for .NET</description>
<authors>James Newton-King</authors> <authors>James Newton-King</authors>
+8 -6
View File
@@ -1,13 +1,14 @@
properties { properties {
$zipFileName = "Json60r6.zip" $zipFileName = "Json60r7.zip"
$majorVersion = "6.0" $majorVersion = "6.0"
$majorWithReleaseVersion = "6.0.6" $majorWithReleaseVersion = "6.0.7"
$version = GetVersion $majorWithReleaseVersion $version = GetVersion $majorWithReleaseVersion
$signAssemblies = $false $signAssemblies = $false
$signKeyPath = "C:\Development\Releases\newtonsoft.snk" $signKeyPath = "C:\Development\Releases\newtonsoft.snk"
$buildDocumentation = $false $buildDocumentation = $false
$buildNuGet = $true $buildNuGet = $true
$treatWarningsAsErrors = $false $treatWarningsAsErrors = $false
$workingName = if ($workingName) {$workingName} else {"Working"}
$baseDir = resolve-path .. $baseDir = resolve-path ..
$buildDir = "$baseDir\Build" $buildDir = "$baseDir\Build"
@@ -15,12 +16,12 @@
$toolsDir = "$baseDir\Tools" $toolsDir = "$baseDir\Tools"
$docDir = "$baseDir\Doc" $docDir = "$baseDir\Doc"
$releaseDir = "$baseDir\Release" $releaseDir = "$baseDir\Release"
$workingDir = "$baseDir\Working" $workingDir = "$baseDir\$workingName"
$builds = @( $builds = @(
@{Name = "Newtonsoft.Json"; TestsName = "Newtonsoft.Json.Tests"; TestsFunction = "NUnitTests"; Constants=""; FinalDir="Net45"; NuGetDir = "net45"; Framework="net-4.0"; Sign=$true}, @{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.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 = "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.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.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}, @{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 task default -depends Test
@@ -38,11 +39,12 @@ task Clean {
if (Test-Path -path $workingDir) if (Test-Path -path $workingDir)
{ {
Write-Output "Deleting Working Directory" Write-Output "Deleting existing working directory $workingDir"
del $workingDir -Recurse -Force del $workingDir -Recurse -Force
} }
Write-Output "Creating working directory $workingDir"
New-Item -Path $workingDir -ItemType Directory New-Item -Path $workingDir -ItemType Directory
} }
@@ -33,4 +33,4 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("6.0.0.0")] // [assembly: AssemblyVersion("6.0.0.0")]
[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); 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 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""> 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> <Value>foo_bar</Value>
@@ -825,6 +825,49 @@ namespace Newtonsoft.Json.Tests
]", sb.ToString()); ]", 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] [Test]
public void BadWriteEndArray() 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; counts[s] = c;
} }
#if !NETFX_CORE
[Test] [Test]
public void DeserializeLargeDynamic() public void DeserializeLargeDynamic()
{ {
@@ -100,6 +101,7 @@ namespace Newtonsoft.Json.Tests.Linq
Console.WriteLine("Time (secs): " + sw.Elapsed.TotalSeconds); Console.WriteLine("Time (secs): " + sw.Elapsed.TotalSeconds);
} }
#endif
[Test] [Test]
public void JObjectPropertyNames() public void JObjectPropertyNames()
@@ -208,8 +208,6 @@ namespace Newtonsoft.Json.Tests.Linq
] ]
}"; }";
StringReader sr = new StringReader(input);
JObject o = JObject.Parse(input); JObject o = JObject.Parse(input);
using (JTokenReader jsonReader = new JTokenReader(o)) using (JTokenReader jsonReader = new JTokenReader(o))
@@ -220,12 +218,14 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(0, lineInfo.LineNumber); Assert.AreEqual(0, lineInfo.LineNumber);
Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(0, lineInfo.LinePosition);
Assert.AreEqual(false, lineInfo.HasLineInfo()); Assert.AreEqual(false, lineInfo.HasLineInfo());
Assert.AreEqual(null, jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject);
Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LineNumber);
Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(1, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o, jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
@@ -233,6 +233,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(2, lineInfo.LineNumber);
Assert.AreEqual(7, lineInfo.LinePosition); Assert.AreEqual(7, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("CPU"), jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
@@ -240,6 +241,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(2, lineInfo.LineNumber);
Assert.AreEqual(15, lineInfo.LinePosition); Assert.AreEqual(15, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("CPU").Value, jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName);
@@ -247,12 +249,14 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(10, lineInfo.LinePosition); Assert.AreEqual(10, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("Drives"), jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray);
Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(12, lineInfo.LinePosition); Assert.AreEqual(12, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o.Property("Drives").Value, jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
@@ -260,6 +264,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(4, lineInfo.LineNumber); Assert.AreEqual(4, lineInfo.LineNumber);
Assert.AreEqual(22, lineInfo.LinePosition); Assert.AreEqual(22, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"][0], jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.TokenType, JsonToken.String);
@@ -267,21 +272,29 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(5, lineInfo.LineNumber); Assert.AreEqual(5, lineInfo.LineNumber);
Assert.AreEqual(30, lineInfo.LinePosition); Assert.AreEqual(30, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"][1], jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray);
Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(3, lineInfo.LineNumber);
Assert.AreEqual(12, lineInfo.LinePosition); Assert.AreEqual(12, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o["Drives"], jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject);
Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LineNumber);
Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(1, lineInfo.LinePosition);
Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(true, lineInfo.HasLineInfo());
Assert.AreEqual(o, jsonReader.CurrentToken);
jsonReader.Read(); jsonReader.Read();
Assert.AreEqual(jsonReader.TokenType, JsonToken.None); 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); JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader(); JTokenReader reader = (JTokenReader)o.CreateReader();
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.AreEqual(o, reader.CurrentToken);
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.AreEqual(o.Property("Name"), reader.CurrentToken);
reader.ReadAsInt32(); reader.ReadAsInt32();
Assert.AreEqual(o["Name"], reader.CurrentToken);
Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(typeof(int), reader.ValueType); Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value); Assert.AreEqual(1, reader.Value);
@@ -717,6 +717,27 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(3, (int)descendants[descendants.Count - 1]); 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] [Test]
public void CreateWriter() 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] [Test]
public void WriteComment() public void WriteComment()
{ {
@@ -213,6 +213,7 @@
<Compile Include="LinqToSql\LinqToSqlClassesSerializationTests.cs" /> <Compile Include="LinqToSql\LinqToSqlClassesSerializationTests.cs" />
<Compile Include="LinqToSql\Person.cs" /> <Compile Include="LinqToSql\Person.cs" />
<Compile Include="LinqToSql\Role.cs" /> <Compile Include="LinqToSql\Role.cs" />
<Compile Include="Linq\AnnotationsTests.cs" />
<Compile Include="Linq\ComponentModel\BindingTests.cs" /> <Compile Include="Linq\ComponentModel\BindingTests.cs" />
<Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" /> <Compile Include="Linq\ComponentModel\JPropertyDescriptorTests.cs" />
<Compile Include="Linq\DynamicTests.cs" /> <Compile Include="Linq\DynamicTests.cs" />
@@ -240,6 +241,7 @@
<Compile Include="Schema\JsonSchemaNodeTests.cs" /> <Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Schema\JsonSchemaSpecTests.cs" /> <Compile Include="Schema\JsonSchemaSpecTests.cs" />
<Compile Include="Schema\JsonSchemaTests.cs" /> <Compile Include="Schema\JsonSchemaTests.cs" />
<Compile Include="Schema\PerformanceTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" /> <Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\ConstructorHandlingTests.cs" /> <Compile Include="Serialization\ConstructorHandlingTests.cs" />
<Compile Include="Serialization\ContractResolverTests.cs" /> <Compile Include="Serialization\ContractResolverTests.cs" />
@@ -76,4 +76,4 @@ using System.Security;
// by using the '*' as shown below: // 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")]
@@ -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); Assert.AreEqual("fff", obj.Field1);
} }
#endif #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 #if !NET20
@@ -8374,6 +8374,46 @@ Path '', line 1, position 1.");
} }
#endif #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 class ErroringJsonConverter : JsonConverter
{ {
public ErroringJsonConverter(string s) public ErroringJsonConverter(string s)
@@ -23,6 +23,11 @@
// OTHER DEALINGS IN THE SOFTWARE. // OTHER DEALINGS IN THE SOFTWARE.
#endregion #endregion
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
#if !(PORTABLE || PORTABLE40) #if !(PORTABLE || PORTABLE40)
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
#if !(NET35 || NET20) #if !(NET35 || NET20)
@@ -1836,6 +1841,55 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(1UL, item.WantedUnitID); Assert.AreEqual(1UL, item.WantedUnitID);
} }
#endif #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) #if !(NETFX_CORE || ASPNETCORE50)
+5 -2
View File
@@ -261,11 +261,14 @@ namespace Newtonsoft.Json.Tests
protected void TestSetup() protected void TestSetup()
#endif #endif
{ {
//#if !NETFX_CORE #if !NETFX_CORE
// CultureInfo turkey = CultureInfo.CreateSpecificCulture("tr"); // CultureInfo turkey = CultureInfo.CreateSpecificCulture("tr");
// Thread.CurrentThread.CurrentCulture = turkey; // Thread.CurrentThread.CurrentCulture = turkey;
// Thread.CurrentThread.CurrentUICulture = turkey; // Thread.CurrentThread.CurrentUICulture = turkey;
//#endif
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
#endif
JsonConvert.DefaultSettings = null; JsonConvert.DefaultSettings = null;
} }
+10 -10
View File
@@ -35,7 +35,7 @@ using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Bson namespace Newtonsoft.Json.Bson
{ {
/// <summary> /// <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> /// </summary>
public class BsonReader : JsonReader public class BsonReader : JsonReader
{ {
@@ -61,15 +61,15 @@ namespace Newtonsoft.Json.Bson
private enum BsonReaderState private enum BsonReaderState
{ {
Normal, Normal = 0,
ReferenceStart, ReferenceStart = 1,
ReferenceRef, ReferenceRef = 2,
ReferenceId, ReferenceId = 3,
CodeWScopeStart, CodeWScopeStart = 4,
CodeWScopeCode, CodeWScopeCode = 5,
CodeWScopeScope, CodeWScopeScope = 6,
CodeWScopeScopeObject, CodeWScopeScopeObject = 7,
CodeWScopeScopeEnd CodeWScopeScopeEnd = 8
} }
private class ContainerContext private class ContainerContext
@@ -79,7 +79,7 @@ namespace Newtonsoft.Json.Converters
case JsonToken.StartArray: case JsonToken.StartArray:
return ReadList(reader); return ReadList(reader);
default: default:
if (JsonReader.IsPrimitiveToken(reader.TokenType)) if (JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
return reader.Value; return reader.Value;
throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); 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> /// <summary>
/// Date formatted strings are not parsed to a date type and are read as strings. /// Date formatted strings are not parsed to a date type and are read as strings.
/// </summary> /// </summary>
None, None = 0,
/// <summary> /// <summary>
/// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to <see cref="DateTime"/>. /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to <see cref="DateTime"/>.
/// </summary> /// </summary>
DateTime, DateTime = 1,
#if !NET20 #if !NET20
/// <summary> /// <summary>
/// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to <see cref="DateTimeOffset"/>. /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to <see cref="DateTimeOffset"/>.
/// </summary> /// </summary>
DateTimeOffset DateTimeOffset = 2
#endif #endif
} }
} }
+4 -4
View File
@@ -35,22 +35,22 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time. /// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time.
/// </summary> /// </summary>
Local, Local = 0,
/// <summary> /// <summary>
/// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC. /// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC.
/// </summary> /// </summary>
Utc, Utc = 1,
/// <summary> /// <summary>
/// Treat as a local time if a <see cref="DateTime"/> is being converted to a string. /// 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. /// If a string is being converted to <see cref="DateTime"/>, convert to a local time if a time zone is specified.
/// </summary> /// </summary>
Unspecified, Unspecified = 2,
/// <summary> /// <summary>
/// Time zone information should be preserved when converting. /// Time zone information should be preserved when converting.
/// </summary> /// </summary>
RoundtripKind RoundtripKind = 3
} }
} }
+3 -3
View File
@@ -34,17 +34,17 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// Write special floating point values as strings in JSON, e.g. "NaN", "Infinity", "-Infinity". /// Write special floating point values as strings in JSON, e.g. "NaN", "Infinity", "-Infinity".
/// </summary> /// </summary>
String, String = 0,
/// <summary> /// <summary>
/// Write special floating point values as symbols in JSON, e.g. NaN, Infinity, -Infinity. /// Write special floating point values as symbols in JSON, e.g. NaN, Infinity, -Infinity.
/// Note that this will produce non-valid JSON. /// Note that this will produce non-valid JSON.
/// </summary> /// </summary>
Symbol, Symbol = 1,
/// <summary> /// <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. /// 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> /// </summary>
DefaultValue DefaultValue = 2
} }
} }
+2 -2
View File
@@ -33,11 +33,11 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// Floating point numbers are parsed to <see cref="Double"/>. /// Floating point numbers are parsed to <see cref="Double"/>.
/// </summary> /// </summary>
Double, Double = 0,
/// <summary> /// <summary>
/// Floating point numbers are parsed to <see cref="Decimal"/>. /// Floating point numbers are parsed to <see cref="Decimal"/>.
/// </summary> /// </summary>
Decimal Decimal = 1
} }
} }
@@ -11,12 +11,12 @@ namespace System.Runtime.Serialization.Formatters
/// <summary> /// <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. /// 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> /// </summary>
Simple, Simple = 0,
/// <summary> /// <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. /// 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> /// </summary>
Full Full = 1
} }
} }
+2 -2
View File
@@ -33,11 +33,11 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// No special formatting is applied. This is the default. /// No special formatting is applied. This is the default.
/// </summary> /// </summary>
None, None = 0,
/// <summary> /// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings. /// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary> /// </summary>
Indented Indented = 1
} }
} }
+4 -4
View File
@@ -33,10 +33,10 @@ namespace Newtonsoft.Json
{ {
internal enum JsonContainerType internal enum JsonContainerType
{ {
None, None = 0,
Object, Object = 1,
Array, Array = 2,
Constructor Constructor = 3
} }
internal struct JsonPosition internal struct JsonPosition
+4 -35
View File
@@ -39,7 +39,7 @@ using System.Linq;
namespace Newtonsoft.Json namespace Newtonsoft.Json
{ {
/// <summary> /// <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> /// </summary>
public abstract class JsonReader : IDisposable public abstract class JsonReader : IDisposable
{ {
@@ -251,7 +251,7 @@ namespace Newtonsoft.Json
get get
{ {
int depth = _stack.Count; int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth; return depth;
else else
return depth + 1; return depth + 1;
@@ -712,7 +712,7 @@ namespace Newtonsoft.Json
if (t == JsonToken.Null) if (t == JsonToken.Null)
return null; return null;
if (IsPrimitiveToken(t)) if (JsonTokenUtils.IsPrimitiveToken(t))
{ {
if (Value != null) if (Value != null)
{ {
@@ -823,7 +823,7 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.PropertyName) if (TokenType == JsonToken.PropertyName)
Read(); Read();
if (IsStartToken(TokenType)) if (JsonTokenUtils.IsStartToken(TokenType))
{ {
int depth = Depth; int depth = Depth;
@@ -963,37 +963,6 @@ namespace Newtonsoft.Json
_currentState = State.Finished; _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) private JsonContainerType GetTypeForCloseToken(JsonToken token)
{ {
switch (token) switch (token)
+1 -1
View File
@@ -37,7 +37,7 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json namespace Newtonsoft.Json
{ {
/// <summary> /// <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> /// </summary>
public class JsonTextWriter : JsonWriter public class JsonTextWriter : JsonWriter
{ {
+18 -18
View File
@@ -37,91 +37,91 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// This is returned by the <see cref="JsonReader"/> if a <see cref="JsonReader.Read"/> method has not been called. /// This is returned by the <see cref="JsonReader"/> if a <see cref="JsonReader.Read"/> method has not been called.
/// </summary> /// </summary>
None, None = 0,
/// <summary> /// <summary>
/// An object start token. /// An object start token.
/// </summary> /// </summary>
StartObject, StartObject = 1,
/// <summary> /// <summary>
/// An array start token. /// An array start token.
/// </summary> /// </summary>
StartArray, StartArray = 2,
/// <summary> /// <summary>
/// A constructor start token. /// A constructor start token.
/// </summary> /// </summary>
StartConstructor, StartConstructor = 3,
/// <summary> /// <summary>
/// An object property name. /// An object property name.
/// </summary> /// </summary>
PropertyName, PropertyName = 4,
/// <summary> /// <summary>
/// A comment. /// A comment.
/// </summary> /// </summary>
Comment, Comment = 5,
/// <summary> /// <summary>
/// Raw JSON. /// Raw JSON.
/// </summary> /// </summary>
Raw, Raw = 6,
/// <summary> /// <summary>
/// An integer. /// An integer.
/// </summary> /// </summary>
Integer, Integer = 7,
/// <summary> /// <summary>
/// A float. /// A float.
/// </summary> /// </summary>
Float, Float = 8,
/// <summary> /// <summary>
/// A string. /// A string.
/// </summary> /// </summary>
String, String = 9,
/// <summary> /// <summary>
/// A boolean. /// A boolean.
/// </summary> /// </summary>
Boolean, Boolean = 10,
/// <summary> /// <summary>
/// A null token. /// A null token.
/// </summary> /// </summary>
Null, Null = 11,
/// <summary> /// <summary>
/// An undefined token. /// An undefined token.
/// </summary> /// </summary>
Undefined, Undefined = 12,
/// <summary> /// <summary>
/// An object end token. /// An object end token.
/// </summary> /// </summary>
EndObject, EndObject = 13,
/// <summary> /// <summary>
/// An array end token. /// An array end token.
/// </summary> /// </summary>
EndArray, EndArray = 14,
/// <summary> /// <summary>
/// A constructor end token. /// A constructor end token.
/// </summary> /// </summary>
EndConstructor, EndConstructor = 15,
/// <summary> /// <summary>
/// A Date. /// A Date.
/// </summary> /// </summary>
Date, Date = 16,
/// <summary> /// <summary>
/// Byte data. /// Byte data.
/// </summary> /// </summary>
Bytes Bytes = 17
} }
} }
+2 -2
View File
@@ -461,7 +461,7 @@ namespace Newtonsoft.Json
JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder(); JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder();
_model = builder.Build(_schema); _model = builder.Build(_schema);
if (!JsonWriter.IsStartToken(_reader.TokenType)) if (!JsonTokenUtils.IsStartToken(_reader.TokenType))
Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas)); Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas));
} }
@@ -578,7 +578,7 @@ namespace Newtonsoft.Json
{ {
if (schemaScope.CurrentItemWriter == null) if (schemaScope.CurrentItemWriter == null)
{ {
if (JsonWriter.IsEndToken(_reader.TokenType)) if (JsonTokenUtils.IsEndToken(_reader.TokenType))
continue; continue;
schemaScope.CurrentItemWriter = new JTokenWriter(); schemaScope.CurrentItemWriter = new JTokenWriter();
+135 -129
View File
@@ -41,22 +41,22 @@ using System.Linq;
namespace Newtonsoft.Json namespace Newtonsoft.Json
{ {
/// <summary> /// <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> /// </summary>
public abstract class JsonWriter : IDisposable public abstract class JsonWriter : IDisposable
{ {
internal enum State internal enum State
{ {
Start, Start = 0,
Property, Property = 1,
ObjectStart, ObjectStart = 2,
Object, Object = 3,
ArrayStart, ArrayStart = 4,
Array, Array = 5,
ConstructorStart, ConstructorStart = 6,
Constructor, Constructor = 7,
Closed, Closed = 8,
Error Error = 9
} }
// array that gives a new state based on the current state an the token being written // 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); 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) internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate)
{ {
int initialDepth; int initialDepth;
if (reader.TokenType == JsonToken.None) if (reader.TokenType == JsonToken.None)
initialDepth = -1; initialDepth = -1;
else if (!IsStartToken(reader.TokenType)) else if (!JsonTokenUtils.IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1; initialDepth = reader.Depth + 1;
else else
initialDepth = reader.Depth; initialDepth = reader.Depth;
@@ -467,103 +489,113 @@ namespace Newtonsoft.Json
{ {
do do
{ {
switch (reader.TokenType) // 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))
case JsonToken.None: WriteConstructorDate(reader);
// read to next else
break; WriteTokenInternal(reader.TokenType, reader.Value);
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.");
}
} while ( } while (
// stop if we have reached the end of the token being read // 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 && writeChildren
&& reader.Read()); && 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) private void WriteConstructorDate(JsonReader reader)
{ {
if (!reader.Read()) if (!reader.Read())
@@ -582,32 +614,6 @@ namespace Newtonsoft.Json
WriteValue(date); 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) private void WriteEnd(JsonContainerType type)
{ {
switch (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> /// <returns>An <see cref="IEnumerable{JToken}"/> containing the descendant tokens of the <see cref="JToken"/>.</returns>
public IEnumerable<JToken> Descendants() 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) foreach (JToken o in ChildrenTokens)
{ {
yield return o; yield return o;
+296 -8
View File
@@ -59,13 +59,15 @@ namespace Newtonsoft.Json.Linq
, IDynamicMetaObjectProvider , IDynamicMetaObjectProvider
#endif #endif
{ {
private static JTokenEqualityComparer _equalityComparer;
private JContainer _parent; private JContainer _parent;
private JToken _previous; private JToken _previous;
private JToken _next; private JToken _next;
private static JTokenEqualityComparer _equalityComparer; private object _annotations;
private int? _lineNumber; //private int? _lineNumber;
private int? _linePosition; //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[] 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 }; 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); 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) internal void SetLineInfo(int lineNumber, int linePosition)
{ {
_lineNumber = lineNumber; AddAnnotation(new LineInfoAnnotation(lineNumber, linePosition));
_linePosition = linePosition;
} }
bool IJsonLineInfo.HasLineInfo() bool IJsonLineInfo.HasLineInfo()
{ {
return (_lineNumber != null && _linePosition != null); return (Annotation<LineInfoAnnotation>() != null);
} }
int IJsonLineInfo.LineNumber int IJsonLineInfo.LineNumber
{ {
get { return _lineNumber ?? 0; } get
{
LineInfoAnnotation annotation = Annotation<LineInfoAnnotation>();
if (annotation != null)
return annotation.LineNumber;
return 0;
}
} }
int IJsonLineInfo.LinePosition int IJsonLineInfo.LinePosition
{ {
get { return _linePosition ?? 0; } get
{
LineInfoAnnotation annotation = Annotation<LineInfoAnnotation>();
if (annotation != null)
return annotation.LinePosition;
return 0;
}
} }
/// <summary> /// <summary>
@@ -2047,5 +2074,266 @@ namespace Newtonsoft.Json.Linq
{ {
return CloneToken(); 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 namespace Newtonsoft.Json.Linq
{ {
/// <summary> /// <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> /// </summary>
public class JTokenReader : JsonReader, IJsonLineInfo public class JTokenReader : JsonReader, IJsonLineInfo
{ {
private readonly string _initialPath; private readonly string _initialPath;
private readonly JToken _root; private readonly JToken _root;
private JToken _parent; 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> /// <summary>
/// Initializes a new instance of the <see cref="JTokenReader"/> class. /// Initializes a new instance of the <see cref="JTokenReader"/> class.
@@ -47,7 +55,6 @@ namespace Newtonsoft.Json.Linq
ValidationUtils.ArgumentNotNull(token, "token"); ValidationUtils.ArgumentNotNull(token, "token");
_root = token; _root = token;
_current = token;
} }
internal JTokenReader(JToken token, string initialPath) internal JTokenReader(JToken token, string initialPath)
@@ -118,6 +125,9 @@ namespace Newtonsoft.Json.Linq
{ {
if (CurrentState != State.Start) if (CurrentState != State.Start)
{ {
if (_current == null)
return false;
JContainer container = _current as JContainer; JContainer container = _current as JContainer;
if (container != null && _parent != container) if (container != null && _parent != container)
return ReadInto(container); return ReadInto(container);
@@ -125,6 +135,7 @@ namespace Newtonsoft.Json.Linq
return ReadOver(_current); return ReadOver(_current);
} }
_current = _root;
SetToken(_current); SetToken(_current);
return true; return true;
} }
@@ -165,6 +176,7 @@ namespace Newtonsoft.Json.Linq
private bool ReadToEnd() private bool ReadToEnd()
{ {
_current = null;
SetToken(JsonToken.None); SetToken(JsonToken.None);
return false; return false;
} }
+18 -18
View File
@@ -33,91 +33,91 @@ namespace Newtonsoft.Json.Linq
/// <summary> /// <summary>
/// No token type has been set. /// No token type has been set.
/// </summary> /// </summary>
None, None = 0,
/// <summary> /// <summary>
/// A JSON object. /// A JSON object.
/// </summary> /// </summary>
Object, Object = 1,
/// <summary> /// <summary>
/// A JSON array. /// A JSON array.
/// </summary> /// </summary>
Array, Array = 2,
/// <summary> /// <summary>
/// A JSON constructor. /// A JSON constructor.
/// </summary> /// </summary>
Constructor, Constructor = 3,
/// <summary> /// <summary>
/// A JSON object property. /// A JSON object property.
/// </summary> /// </summary>
Property, Property = 4,
/// <summary> /// <summary>
/// A comment. /// A comment.
/// </summary> /// </summary>
Comment, Comment = 5,
/// <summary> /// <summary>
/// An integer value. /// An integer value.
/// </summary> /// </summary>
Integer, Integer = 6,
/// <summary> /// <summary>
/// A float value. /// A float value.
/// </summary> /// </summary>
Float, Float = 7,
/// <summary> /// <summary>
/// A string value. /// A string value.
/// </summary> /// </summary>
String, String = 8,
/// <summary> /// <summary>
/// A boolean value. /// A boolean value.
/// </summary> /// </summary>
Boolean, Boolean = 9,
/// <summary> /// <summary>
/// A null value. /// A null value.
/// </summary> /// </summary>
Null, Null = 10,
/// <summary> /// <summary>
/// An undefined value. /// An undefined value.
/// </summary> /// </summary>
Undefined, Undefined = 11,
/// <summary> /// <summary>
/// A date value. /// A date value.
/// </summary> /// </summary>
Date, Date = 12,
/// <summary> /// <summary>
/// A raw JSON value. /// A raw JSON value.
/// </summary> /// </summary>
Raw, Raw = 13,
/// <summary> /// <summary>
/// A collection of bytes value. /// A collection of bytes value.
/// </summary> /// </summary>
Bytes, Bytes = 14,
/// <summary> /// <summary>
/// A Guid value. /// A Guid value.
/// </summary> /// </summary>
Guid, Guid = 15,
/// <summary> /// <summary>
/// A Uri value. /// A Uri value.
/// </summary> /// </summary>
Uri, Uri = 16,
/// <summary> /// <summary>
/// A TimeSpan value. /// A TimeSpan value.
/// </summary> /// </summary>
TimeSpan TimeSpan = 17
} }
} }
+14 -1
View File
@@ -33,7 +33,7 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq namespace Newtonsoft.Json.Linq
{ {
/// <summary> /// <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> /// </summary>
public class JTokenWriter : JsonWriter public class JTokenWriter : JsonWriter
{ {
@@ -41,6 +41,15 @@ namespace Newtonsoft.Json.Linq
private JContainer _parent; private JContainer _parent;
// used when writer is writing single value and the value has no containing parent // used when writer is writing single value and the value has no containing parent
private JValue _value; 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> /// <summary>
/// Gets the token being writen. /// Gets the token being writen.
@@ -109,10 +118,12 @@ namespace Newtonsoft.Json.Linq
_parent.AddAndSkipParentCheck(container); _parent.AddAndSkipParentCheck(container);
_parent = container; _parent = container;
_current = container;
} }
private void RemoveParent() private void RemoveParent()
{ {
_current = _parent;
_parent = _parent.Parent; _parent = _parent.Parent;
if (_parent != null && _parent.Type == JTokenType.Property) if (_parent != null && _parent.Type == JTokenType.Property)
@@ -172,6 +183,7 @@ namespace Newtonsoft.Json.Linq
if (_parent != null) if (_parent != null)
{ {
_parent.Add(value); _parent.Add(value);
_current = _parent.Last;
if (_parent.Type == JTokenType.Property) if (_parent.Type == JTokenType.Property)
_parent = _parent.Parent; _parent = _parent.Parent;
@@ -179,6 +191,7 @@ namespace Newtonsoft.Json.Linq
else else
{ {
_value = value ?? JValue.CreateNull(); _value = value ?? JValue.CreateNull();
_current = _value;
} }
} }
@@ -5,16 +5,16 @@ namespace Newtonsoft.Json.Linq.JsonPath
{ {
internal enum QueryOperator internal enum QueryOperator
{ {
None, None = 0,
Equals, Equals = 1,
NotEquals, NotEquals = 2,
Exists, Exists = 3,
LessThan, LessThan = 4,
LessThanOrEquals, LessThanOrEquals = 5,
GreaterThan, GreaterThan = 6,
GreaterThanOrEquals, GreaterThanOrEquals = 7,
And, And = 8,
Or Or = 9
} }
internal abstract class QueryExpression internal abstract class QueryExpression
@@ -6,15 +6,15 @@ namespace Newtonsoft.Json.Linq
public enum MergeArrayHandling public enum MergeArrayHandling
{ {
/// <summary>Concatenate arrays.</summary> /// <summary>Concatenate arrays.</summary>
Concat, Concat = 0,
/// <summary>Union arrays, skipping items that already exist.</summary> /// <summary>Union arrays, skipping items that already exist.</summary>
Union, Union = 1,
/// <summary>Replace all array items.</summary> /// <summary>Replace all array items.</summary>
Replace, Replace = 2,
/// <summary>Merge array items together, matched by index.</summary> /// <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"/>. /// 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. /// This is the default member serialization mode.
/// </summary> /// </summary>
OptOut, OptOut = 0,
/// <summary> /// <summary>
/// Only members must be marked with <see cref="JsonPropertyAttribute"/> or <see cref="DataMemberAttribute"/> are serialized. /// 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"/>. /// This member serialization mode can also be set by marking the class with <see cref="DataContractAttribute"/>.
/// </summary> /// </summary>
OptIn, OptIn = 1,
/// <summary> /// <summary>
/// All public and private fields are serialized. Members can be excluded using <see cref="JsonIgnoreAttribute"/> or <see cref="NonSerializedAttribute"/>. /// 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"/> /// 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. /// and setting IgnoreSerializableAttribute on <see cref="DefaultContractResolver"/> to false.
/// </summary> /// </summary>
Fields Fields = 2
#pragma warning restore 1584,1711,1572,1581,1580,1574 #pragma warning restore 1584,1711,1572,1581,1580,1574
} }
} }
@@ -136,6 +136,7 @@
<Compile Include="Utilities\DynamicUtils.cs" /> <Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" /> <Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" /> <Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" /> <Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Linq\JPropertyDescriptor.cs" /> <Compile Include="Linq\JPropertyDescriptor.cs" />
<Compile Include="Linq\JRaw.cs" /> <Compile Include="Linq\JRaw.cs" />
@@ -244,6 +244,7 @@
<Compile Include="Utilities\FSharpUtils.cs" /> <Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" /> <Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" /> <Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" /> <Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" /> <Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" /> <Compile Include="Utilities\ReflectionDelegateFactory.cs" />
@@ -244,6 +244,7 @@
<Compile Include="Utilities\FSharpUtils.cs" /> <Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" /> <Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" /> <Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" /> <Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" /> <Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" /> <Compile Include="Utilities\ReflectionDelegateFactory.cs" />
@@ -216,6 +216,7 @@
<Compile Include="Utilities\ILGeneratorExtensions.cs" /> <Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" /> <Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" /> <Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" /> <Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" /> <Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\MathUtils.cs" /> <Compile Include="Utilities\MathUtils.cs" />
@@ -220,6 +220,7 @@
<Compile Include="Utilities\FSharpUtils.cs" /> <Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" /> <Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" /> <Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" /> <Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" /> <Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\MathUtils.cs" /> <Compile Include="Utilities\MathUtils.cs" />
@@ -213,6 +213,7 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" /> <Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" /> <Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" /> <Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" /> <Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionObject.cs" /> <Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\EnumUtils.cs" /> <Compile Include="Utilities\EnumUtils.cs" />
@@ -53,9 +53,10 @@ using System.Security;
#endif #endif
#if !SIGNED #if !SIGNED
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")]
#else #else
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
#endif #endif
@@ -91,5 +92,5 @@ using System.Security;
// by using the '*' as shown below: // 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")]
[assembly: CLSCompliant(true)] [assembly: CLSCompliant(true)]
+3 -3
View File
@@ -33,16 +33,16 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// The property is not required. The default state. /// The property is not required. The default state.
/// </summary> /// </summary>
Default, Default = 0,
/// <summary> /// <summary>
/// The property must be defined in JSON but can be a null value. /// The property must be defined in JSON but can be a null value.
/// </summary> /// </summary>
AllowNull, AllowNull = 1,
/// <summary> /// <summary>
/// The property must be defined in JSON and cannot be a null value. /// The property must be defined in JSON and cannot be a null value.
/// </summary> /// </summary>
Always Always = 2
} }
} }
@@ -35,19 +35,15 @@ namespace Newtonsoft.Json.Serialization
{ {
internal enum JsonContractType internal enum JsonContractType
{ {
None, None = 0,
Object, Object = 1,
Array, Array = 2,
Primitive, Primitive = 3,
String, String = 4,
Dictionary, Dictionary = 5,
#if !(NET35 || NET20 || PORTABLE40) Dynamic = 6,
Dynamic, Serializable = 7,
#endif Linq = 8
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
Serializable,
#endif
Linq
} }
/// <summary> /// <summary>
@@ -52,9 +52,9 @@ namespace Newtonsoft.Json.Serialization
{ {
internal enum PropertyPresence internal enum PropertyPresence
{ {
None, None = 0,
Null, Null = 1,
Value Value = 2
} }
private JsonSerializerProxy _internalSerializer; private JsonSerializerProxy _internalSerializer;
@@ -526,7 +526,7 @@ namespace Newtonsoft.Json.Serialization
if (reader.TokenType == JsonToken.StartObject) if (reader.TokenType == JsonToken.StartObject)
{ {
JObject current = (JObject)reader._current; JObject current = (JObject)reader.CurrentToken;
JToken refToken = current[JsonTypeReflector.RefPropertyName]; JToken refToken = current[JsonTypeReflector.RefPropertyName];
if (refToken != null) 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 // 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) if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)
&& JsonReader.IsPrimitiveToken(tokenType) && JsonTokenUtils.IsPrimitiveToken(tokenType)
&& MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue())) && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue()))
return true; return true;
@@ -1563,7 +1563,7 @@ namespace Newtonsoft.Json.Serialization
} }
else 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); JsonContract dynamicMemberContract = GetContractSafe(t);
JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member);
+3 -3
View File
@@ -33,16 +33,16 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// Only control characters (e.g. newline) are escaped. /// Only control characters (e.g. newline) are escaped.
/// </summary> /// </summary>
Default, Default = 0,
/// <summary> /// <summary>
/// All non-ASCII and control characters (e.g. newline) are escaped. /// All non-ASCII and control characters (e.g. newline) are escaped.
/// </summary> /// </summary>
EscapeNonAscii, EscapeNonAscii = 1,
/// <summary> /// <summary>
/// HTML (&lt;, &gt;, &amp;, &apos;, &quot;) and control characters (e.g. newline) are escaped. /// HTML (&lt;, &gt;, &amp;, &apos;, &quot;) and control characters (e.g. newline) are escaped.
/// </summary> /// </summary>
EscapeHtml EscapeHtml = 2
} }
} }
+5 -5
View File
@@ -12,27 +12,27 @@ namespace Newtonsoft.Json
/// <summary> /// <summary>
/// Output no tracing and debugging messages. /// Output no tracing and debugging messages.
/// </summary> /// </summary>
Off, Off = 0,
/// <summary> /// <summary>
/// Output error-handling messages. /// Output error-handling messages.
/// </summary> /// </summary>
Error, Error = 1,
/// <summary> /// <summary>
/// Output warnings and error-handling messages. /// Output warnings and error-handling messages.
/// </summary> /// </summary>
Warning, Warning = 2,
/// <summary> /// <summary>
/// Output informational messages, warnings, and error-handling messages. /// Output informational messages, warnings, and error-handling messages.
/// </summary> /// </summary>
Info, Info = 3,
/// <summary> /// <summary>
/// Output all debugging and tracing messages. /// Output all debugging and tracing messages.
/// </summary> /// </summary>
Verbose Verbose = 4
} }
} }
+50 -54
View File
@@ -46,52 +46,48 @@ namespace Newtonsoft.Json.Utilities
{ {
internal enum PrimitiveTypeCode internal enum PrimitiveTypeCode
{ {
Empty, Empty = 0,
Object, Object = 1,
Char, Char = 2,
CharNullable, CharNullable = 3,
Boolean, Boolean = 4,
BooleanNullable, BooleanNullable = 5,
SByte, SByte = 6,
SByteNullable, SByteNullable = 7,
Int16, Int16 = 8,
Int16Nullable, Int16Nullable = 9,
UInt16, UInt16 = 10,
UInt16Nullable, UInt16Nullable = 11,
Int32, Int32 = 12,
Int32Nullable, Int32Nullable = 13,
Byte, Byte = 14,
ByteNullable, ByteNullable = 15,
UInt32, UInt32 = 16,
UInt32Nullable, UInt32Nullable = 17,
Int64, Int64 = 18,
Int64Nullable, Int64Nullable = 19,
UInt64, UInt64 = 20,
UInt64Nullable, UInt64Nullable = 21,
Single, Single = 22,
SingleNullable, SingleNullable = 23,
Double, Double = 24,
DoubleNullable, DoubleNullable = 25,
DateTime, DateTime = 26,
DateTimeNullable, DateTimeNullable = 27,
#if !NET20 DateTimeOffset = 28,
DateTimeOffset, DateTimeOffsetNullable = 29,
DateTimeOffsetNullable, Decimal = 30,
#endif DecimalNullable = 31,
Decimal, Guid = 32,
DecimalNullable, GuidNullable = 33,
Guid, TimeSpan = 34,
GuidNullable, TimeSpanNullable = 35,
TimeSpan, BigInteger = 36,
TimeSpanNullable, BigIntegerNullable = 37,
#if !(PORTABLE || NET35 || NET20) Uri = 38,
BigInteger, String = 39,
BigIntegerNullable, Bytes = 40,
#endif DBNull = 41
Uri,
String,
Bytes,
DBNull
} }
internal class TypeInformation internal class TypeInformation
@@ -102,10 +98,10 @@ namespace Newtonsoft.Json.Utilities
internal enum ParseResult internal enum ParseResult
{ {
None, None = 0,
Success, Success = 1,
Overflow, Overflow = 2,
Invalid Invalid = 3
} }
internal static class ConvertUtils internal static class ConvertUtils
@@ -360,10 +356,10 @@ namespace Newtonsoft.Json.Utilities
#region TryConvert #region TryConvert
internal enum ConvertResult internal enum ConvertResult
{ {
Success, Success = 0,
CannotConvertNull, CannotConvertNull = 1,
NotInstantiableType, NotInstantiableType = 2,
NoValidConversion NoValidConversion = 3
} }
public static object Convert(object initialValue, CultureInfo culture, Type targetType) public static object Convert(object initialValue, CultureInfo culture, Type targetType)
@@ -29,10 +29,10 @@ namespace Newtonsoft.Json.Utilities
{ {
internal enum ParserTimeZone internal enum ParserTimeZone
{ {
Unspecified, Unspecified = 0,
Utc, Utc = 1,
LocalWestOfUtc, LocalWestOfUtc = 2,
LocalEastOfUtc LocalEastOfUtc = 3
} }
internal struct DateTimeParser 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) #if (NETFX_CORE || PORTABLE || PORTABLE40)
internal enum MemberTypes internal enum MemberTypes
{ {
Property, Property = 0,
Field, Field = 1,
Event, Event = 2,
Method, Method = 3,
Other Other = 4
} }
#endif #endif
@@ -76,6 +76,14 @@ namespace Newtonsoft.Json.Utilities
{ {
return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo()); 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 #endif
public static MethodInfo Method(this Delegate d) 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. /// 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. /// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown.
/// </summary> /// </summary>
Error, Error = 0,
/// <summary> /// <summary>
/// The <see cref="JsonWriter.Close"/> method has been called. /// The <see cref="JsonWriter.Close"/> method has been called.
/// </summary> /// </summary>
Closed, Closed = 1,
/// <summary> /// <summary>
/// An object is being written. /// An object is being written.
/// </summary> /// </summary>
Object, Object = 2,
/// <summary> /// <summary>
/// A array is being written. /// A array is being written.
/// </summary> /// </summary>
Array, Array = 3,
/// <summary> /// <summary>
/// A constructor is being written. /// A constructor is being written.
/// </summary> /// </summary>
Constructor, Constructor = 4,
/// <summary> /// <summary>
/// A property is being written. /// A property is being written.
/// </summary> /// </summary>
Property, Property = 5,
/// <summary> /// <summary>
/// A write method has not been called. /// A write method has not been called.
/// </summary> /// </summary>
Start Start = 6
} }
} }
+823 -1171
View File
File diff suppressed because it is too large Load Diff