-Fixed null reference error when using JEnumerable created with default constructor

-Tests
This commit is contained in:
James Newton-King
2014-09-25 20:28:47 +12:00
parent b3e667fa78
commit 64ffa098b9
24 changed files with 225382 additions and 15 deletions
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{3CC9C2DF-CD0A-4096-BF46-B4AFDF0147D2}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Newtonsoft.Json.TestConsole</RootNamespace>
<AssemblyName>Newtonsoft.Json.TestConsole</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.csproj">
<Project>{ccd1b8c4-7349-409c-a090-a9b9a1abd981}</Project>
<Name>Newtonsoft.Json.Tests</Name>
</ProjectReference>
<ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.csproj">
<Project>{eeea67f9-9089-481d-a4dc-0966dec9fd7d}</Project>
<Name>Newtonsoft.Json</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Tests;
namespace Newtonsoft.Json.TestConsole
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Json.NET Test Console");
Console.ReadKey();
Console.WriteLine("Doing stuff...");
PerformanceTests t = new PerformanceTests();
//t.BenchmarkSerializeMethod(PerformanceTests.SerializeMethod.JsonNet, new { hello = "world" });
t.DeserializeLargeJson();
Console.WriteLine();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Json.NET Test Console")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyProduct("Json.NET Tests")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bf0cc842-d368-4800-9614-b5abcc736110")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.5.17725")]
@@ -25,6 +25,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
@@ -1007,6 +1008,8 @@ namespace Newtonsoft.Json.Tests
settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
var json = JsonConvert.SerializeObject(dict, settings);
Console.WriteLine(json);
var newDict = new Dictionary<string, object>();
JsonConvert.PopulateObject(json, newDict, settings);
@@ -1014,8 +1017,57 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual(date, now);
}
[Test]
public void MaximumDateTimeOffsetLength()
{
DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0));
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
Console.WriteLine(sw.ToString());
Console.WriteLine(sw.ToString().Length);
}
#endif
[Test]
public void MaximumDateTimeLength()
{
DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local);
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
Console.WriteLine(sw.ToString());
Console.WriteLine(sw.ToString().Length);
}
[Test]
public void MaximumDateTimeMicrosoftDateFormatLength()
{
DateTime dt = DateTime.MaxValue;
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
writer.WriteValue(dt);
writer.Flush();
Console.WriteLine(sw.ToString());
Console.WriteLine(sw.ToString().Length);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
[Test]
public void IntegerLengthOverflows()
@@ -1031,6 +1083,17 @@ namespace Newtonsoft.Json.Tests
}
#endif
[Test]
public void ParseIsoDate()
{
StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00""");
JsonReader jsonReader = new JsonTextReader(sr);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(typeof(DateTime), jsonReader.ValueType);
}
//[Test]
public void StackOverflowTest()
{
@@ -24,6 +24,7 @@
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
#if !NETFX_CORE
@@ -49,6 +50,44 @@ namespace Newtonsoft.Json.Tests.Linq
[TestFixture]
public class LinqToJsonTest : TestFixtureBase
{
[Test]
public void EmptyJEnumerableCount()
{
JEnumerable<JToken> tokens = new JEnumerable<JToken>();
Assert.AreEqual(0, tokens.Count());
}
[Test]
public void EmptyJEnumerableAsEnumerable()
{
IEnumerable tokens = new JEnumerable<JToken>();
Assert.AreEqual(0, tokens.Cast<JToken>().Count());
}
[Test]
public void EmptyJEnumerableEquals()
{
JEnumerable<JToken> tokens1 = new JEnumerable<JToken>();
JEnumerable<JToken> tokens2 = new JEnumerable<JToken>();
Assert.IsTrue(tokens1.Equals(tokens2));
object o1 = new JEnumerable<JToken>();
object o2 = new JEnumerable<JToken>();
Assert.IsTrue(o1.Equals(o2));
}
[Test]
public void EmptyJEnumerableGetHashCode()
{
JEnumerable<JToken> tokens = new JEnumerable<JToken>();
Assert.AreEqual(0, tokens.GetHashCode());
}
[Test]
public void CommentsAndReadFrom()
{
@@ -298,6 +298,7 @@
</ItemGroup>
<ItemGroup>
<Service Include="{3259AA49-8AA1-44D3-9025-A0B520596A8C}" />
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.Net20.csproj">
@@ -338,6 +339,11 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -339,6 +339,9 @@
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="LinqToSql\LinqToSqlClasses.dbml">
<Generator>MSLinqToSQLGenerator</Generator>
<LastGenOutput>LinqToSqlClasses.designer.cs</LastGenOutput>
@@ -461,6 +461,9 @@
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="LinqToSql\LinqToSqlClasses.dbml">
<Generator>MSLinqToSQLGenerator</Generator>
<LastGenOutput>LinqToSqlClasses.designer.cs</LastGenOutput>
@@ -379,6 +379,11 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -386,6 +386,11 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -417,6 +417,9 @@
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="LinqToSql\LinqToSqlClasses.dbml">
<Generator>MSLinqToSQLGenerator</Generator>
<LastGenOutput>LinqToSqlClasses.designer.cs</LastGenOutput>
@@ -132,6 +132,67 @@ namespace Newtonsoft.Json.Tests
SerializeTests(test);
}
[Test]
public void ReadLargeJson()
{
for (int i = 0; i < 100; i++)
{
using (var fs = System.IO.File.OpenText("large.json"))
using (JsonTextReader jsonTextReader = new JsonTextReader(fs))
{
while (jsonTextReader.Read())
{
}
}
}
}
public class Friend
{
public int id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int index { get; set; }
public Guid guid { get; set; }
public bool isActive { get; set; }
public string balance { get; set; }
public string picture { get; set; }
public int age { get; set; }
public string eyeColor { get; set; }
public string name { get; set; }
public string gender { get; set; }
public string company { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string address { get; set; }
public string about { get; set; }
public string registered { get; set; }
public double latitude { get; set; }
public decimal longitude { get; set; }
public List<string> tags { get; set; }
public List<Friend> friends { get; set; }
public string greeting { get; set; }
public string favoriteFruit { get; set; }
}
[Test]
public void DeserializeLargeJson()
{
for (int i = 0; i < 100; i++)
{
using (var fs = System.IO.File.OpenText("large.json"))
using (JsonTextReader jsonTextReader = new JsonTextReader(fs))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Deserialize<IList<RootObject>>(jsonTextReader);
}
}
}
[Test]
public void SerializeKeyValuePair()
{
@@ -42,7 +42,6 @@ using System.Security;
#elif NET40
[assembly: AssemblyTitle("Json.NET Tests .NET 4.0")]
#else
[assembly: AssemblyTitle("Json.NET Tests")]
#endif
@@ -75,4 +74,4 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.5.17712")]
[assembly: AssemblyFileVersion("6.0.5.17725")]
File diff suppressed because it is too large Load Diff
+8 -1
View File
@@ -1,11 +1,14 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json", "Newtonsoft.Json\Newtonsoft.Json.csproj", "{EEEA67F9-9089-481D-A4DC-0966DEC9FD7D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.csproj", "{CCD1B8C4-7349-409C-A090-A9B9A1ABD981}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.TestConsole", "Newtonsoft.Json.TestConsole\Newtonsoft.Json.TestConsole.csproj", "{3CC9C2DF-CD0A-4096-BF46-B4AFDF0147D2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -20,6 +23,10 @@ Global
{CCD1B8C4-7349-409C-A090-A9B9A1ABD981}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCD1B8C4-7349-409C-A090-A9B9A1ABD981}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CCD1B8C4-7349-409C-A090-A9B9A1ABD981}.Release|Any CPU.Build.0 = Release|Any CPU
{3CC9C2DF-CD0A-4096-BF46-B4AFDF0147D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3CC9C2DF-CD0A-4096-BF46-B4AFDF0147D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3CC9C2DF-CD0A-4096-BF46-B4AFDF0147D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3CC9C2DF-CD0A-4096-BF46-B4AFDF0147D2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -120,9 +120,11 @@ namespace Newtonsoft.Json.Converters
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullableType(objectType);
#if !NET20
Type t = (nullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
#endif
if (reader.TokenType == JsonToken.Null)
{
@@ -78,9 +78,11 @@ namespace Newtonsoft.Json.Converters
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
#if !NET20
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
#endif
if (reader.TokenType == JsonToken.Null)
{
+3 -5
View File
@@ -683,13 +683,11 @@ namespace Newtonsoft.Json
private void EnsureWriteBuffer()
{
if (_writeBuffer == null)
_writeBuffer = new char[64];
_writeBuffer = new char[35]; // maximum buffer sized used when writing iso date
}
private void WriteIntegerValue(long value)
{
EnsureWriteBuffer();
if (value >= 0 && value <= 9)
{
_writer.Write((char)('0' + value));
@@ -707,14 +705,14 @@ namespace Newtonsoft.Json
private void WriteIntegerValue(ulong uvalue)
{
EnsureWriteBuffer();
if (uvalue <= 9)
{
_writer.Write((char)('0' + uvalue));
}
else
{
EnsureWriteBuffer();
int totalLength = MathUtils.IntLength(uvalue);
int length = 0;
+28 -3
View File
@@ -23,6 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
@@ -38,7 +39,7 @@ namespace Newtonsoft.Json.Linq
/// Represents a collection of <see cref="JToken"/> objects.
/// </summary>
/// <typeparam name="T">The type of token</typeparam>
public struct JEnumerable<T> : IJEnumerable<T> where T : JToken
public struct JEnumerable<T> : IJEnumerable<T>, IEquatable<JEnumerable<T>> where T : JToken
{
/// <summary>
/// An empty collection of <see cref="JToken"/> objects.
@@ -66,6 +67,9 @@ namespace Newtonsoft.Json.Linq
/// </returns>
public IEnumerator<T> GetEnumerator()
{
if (_enumerable == null)
return Empty.GetEnumerator();
return _enumerable.GetEnumerator();
}
@@ -86,7 +90,25 @@ namespace Newtonsoft.Json.Linq
/// <value></value>
public IJEnumerable<JToken> this[object key]
{
get { return new JEnumerable<JToken>(Extensions.Values<T, JToken>(_enumerable, key)); }
get
{
if (_enumerable == null)
return JEnumerable<JToken>.Empty;
return new JEnumerable<JToken>(_enumerable.Values<T, JToken>(key));
}
}
/// <summary>
/// Determines whether the specified <see cref="JEnumerable{T}"/> is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="JEnumerable{T}"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="JEnumerable{T}"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(JEnumerable<T> other)
{
return Equals(_enumerable, other._enumerable);
}
/// <summary>
@@ -99,7 +121,7 @@ namespace Newtonsoft.Json.Linq
public override bool Equals(object obj)
{
if (obj is JEnumerable<T>)
return _enumerable.Equals(((JEnumerable<T>)obj)._enumerable);
return Equals((JEnumerable<T>)obj);
return false;
}
@@ -112,6 +134,9 @@ namespace Newtonsoft.Json.Linq
/// </returns>
public override int GetHashCode()
{
if (_enumerable == null)
return 0;
return _enumerable.GetHashCode();
}
}
@@ -91,5 +91,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.5.17712")]
[assembly: AssemblyFileVersion("6.0.5.17725")]
[assembly: CLSCompliant(true)]
@@ -95,7 +95,7 @@ namespace Newtonsoft.Json.Serialization
get { return _instance; }
}
private static readonly IList<JsonConverter> BuiltInConverters = new List<JsonConverter>
private static readonly JsonConverter[] BuiltInConverters =
{
#if !(NET20 || NETFX_CORE || PORTABLE40 || PORTABLE)
new EntityKeyMemberConverter(),
@@ -162,7 +162,7 @@ namespace Newtonsoft.Json.Utilities
};
#if !(NETFX_CORE || PORTABLE)
private static readonly List<TypeInformation> PrimitiveTypeCodes = new List<TypeInformation>
private static readonly TypeInformation[] PrimitiveTypeCodes =
{
new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty },
new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Object },
@@ -51,7 +51,7 @@ namespace Newtonsoft.Json.Utilities
public static TimeSpan GetUtcOffset(this DateTime d)
{
#if NET20
return TimeZone.CurrentTimeZone.GetUtcOffset(d);
return TimeZone.CurrentTimeZone.GetUtcOffset(d);
#else
return TimeZoneInfo.Local.GetUtcOffset(d);
#endif
@@ -323,12 +323,16 @@ namespace Newtonsoft.Json.Utilities
if (index == -1)
index = value.IndexOf('-', 1);
#if !NET20
TimeSpan offset = TimeSpan.Zero;
#endif
if (index != -1)
{
kind = DateTimeKind.Local;
#if !NET20
offset = ReadOffset(value.Substring(index));
#endif
value = value.Substring(0, index);
}
@@ -395,6 +399,7 @@ namespace Newtonsoft.Json.Utilities
return false;
}
#if !NET20
private static TimeSpan ReadOffset(string offsetText)
{
bool negative = (offsetText[0] == '-');
@@ -410,6 +415,7 @@ namespace Newtonsoft.Json.Utilities
return offset;
}
#endif
#endregion
#region Write