-6.0.2 merge
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>Newtonsoft.Json</id>
|
||||
<version>6.0.1</version>
|
||||
<version>6.0.2</version>
|
||||
<title>Json.NET</title>
|
||||
<description>Json.NET is a popular high-performance JSON framework for .NET</description>
|
||||
<authors>James Newton-King</authors>
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
properties {
|
||||
$zipFileName = "Json60r1.zip"
|
||||
$majorVersion = "4.5"
|
||||
$majorWithReleaseVersion = "6.0.1"
|
||||
$zipFileName = "Json60r2.zip"
|
||||
$majorVersion = "6.0"
|
||||
$majorWithReleaseVersion = "6.0.2"
|
||||
$version = GetVersion $majorWithReleaseVersion
|
||||
$signAssemblies = $false
|
||||
$signKeyPath = "C:\Development\Releases\newtonsoft.snk"
|
||||
@@ -18,7 +18,7 @@
|
||||
$workingDir = "$baseDir\Working"
|
||||
$builds = @(
|
||||
@{Name = "Newtonsoft.Json"; TestsName = "Newtonsoft.Json.Tests"; Constants=""; FinalDir="Net45"; NuGetDir = "net45"; Framework="net-4.0"; Sign=$true},
|
||||
@{Name = "Newtonsoft.Json.Portable"; TestsName = "Newtonsoft.Json.Tests.Portable"; Constants="PORTABLE"; FinalDir="Portable"; NuGetDir = "portable-net45+wp80+win8+wpx81"; Framework="net-4.0"; Sign=$true},
|
||||
@{Name = "Newtonsoft.Json.Portable"; TestsName = "Newtonsoft.Json.Tests.Portable"; Constants="PORTABLE"; FinalDir="Portable"; NuGetDir = "portable-net45+wp80+win8+wpa81"; Framework="net-4.0"; Sign=$true},
|
||||
@{Name = "Newtonsoft.Json.Portable40"; TestsName = "Newtonsoft.Json.Tests.Portable40"; Constants="PORTABLE40"; FinalDir="Portable40"; NuGetDir = "portable-net40+sl4+wp7+win8"; Framework="net-4.0"; Sign=$true},
|
||||
@{Name = "Newtonsoft.Json.WinRT"; TestsName = $null; Constants="NETFX_CORE"; FinalDir="WinRT"; NuGetDir = "netcore45"; Framework="net-4.5"; Sign=$true},
|
||||
@{Name = "Newtonsoft.Json.Net40"; TestsName = "Newtonsoft.Json.Tests.Net40"; Constants="NET40"; FinalDir="Net40"; NuGetDir = "net40"; Framework="net-4.0"; Sign=$true},
|
||||
|
||||
@@ -13,6 +13,22 @@
|
||||
<linkTarget>_blank</linkTarget>
|
||||
</externalLink></para>
|
||||
</introduction>
|
||||
|
||||
<alert class="caution">
|
||||
<para>
|
||||
The JSON Schema standard isn't final.
|
||||
|
||||
Json.NET implements
|
||||
<externalLink>
|
||||
<linkText>JSON Schema Draft 3</linkText>
|
||||
<linkUri>http://tools.ietf.org/search/draft-zyp-json-schema-03/</linkUri>
|
||||
<linkTarget>_blank</linkTarget>
|
||||
</externalLink>.
|
||||
|
||||
There will be breaking changes to some parts of Json.NET's JSON Schema API when it is updated to implement newer drafts of JSON Schema.
|
||||
</para>
|
||||
</alert>
|
||||
|
||||
<!-- Optional procedures followed by optional code example but must have
|
||||
at least one procedure or code example -->
|
||||
<section>
|
||||
|
||||
+5
-7
@@ -1,7 +1,7 @@
|
||||
Json.NET
|
||||
|
||||
http://james.newtonking.com/projects/json-net.aspx
|
||||
http://www.codeplex.com/json/
|
||||
http://james.newtonking.com/json
|
||||
http://www.codeplex.com/json
|
||||
https://github.com/JamesNK/Newtonsoft.Json
|
||||
|
||||
|
||||
@@ -45,12 +45,10 @@ Json.NET has different libraries for the various .NET Framework versions.
|
||||
.NET 4.5, Windows Phone 8, Windows 8 Store
|
||||
|
||||
-Portable40:
|
||||
.NET 4.0, Windows Phone 7, Windows 8 Store, Silverlight 4
|
||||
.NET 4.0, Windows Phone 8, Windows 8 Store, Silverlight 5, MonoTouch, MonoDroid
|
||||
|
||||
|
||||
Notes:
|
||||
|
||||
Microsoft stopped support for the Compact Framework in Visual Studio 2010.
|
||||
For a Compact Framework 3.5 build download Json.NET 3.5.
|
||||
|
||||
For a Silverlight 3.0 build download Json.NET 3.5.
|
||||
For a Compact Framework 3.5 and Silverlight 3.0 builds download Json.NET 3.5
|
||||
For a Silverlight 4.0 and Windows Phone 7 builds download Json.NET 5
|
||||
@@ -879,12 +879,16 @@ now brown cow?", '"', true);
|
||||
{
|
||||
Task<string> task = null;
|
||||
|
||||
#pragma warning disable 612,618
|
||||
task = JsonConvert.SerializeObjectAsync(42);
|
||||
#pragma warning restore 612,618
|
||||
task.Wait();
|
||||
|
||||
Assert.AreEqual("42", task.Result);
|
||||
|
||||
#pragma warning disable 612,618
|
||||
task = JsonConvert.SerializeObjectAsync(new[] { 1, 2, 3, 4, 5 }, Formatting.Indented);
|
||||
#pragma warning restore 612,618
|
||||
task.Wait();
|
||||
|
||||
Assert.AreEqual(@"[
|
||||
@@ -895,23 +899,29 @@ now brown cow?", '"', true);
|
||||
5
|
||||
]", task.Result);
|
||||
|
||||
#pragma warning disable 612,618
|
||||
task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings
|
||||
{
|
||||
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
|
||||
});
|
||||
#pragma warning restore 612,618
|
||||
task.Wait();
|
||||
|
||||
Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result);
|
||||
|
||||
#pragma warning disable 612,618
|
||||
var taskObject = JsonConvert.DeserializeObjectAsync("[]");
|
||||
#pragma warning restore 612,618
|
||||
taskObject.Wait();
|
||||
|
||||
CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result);
|
||||
|
||||
#pragma warning disable 612,618
|
||||
Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings
|
||||
{
|
||||
Converters = { new VersionConverter() }
|
||||
});
|
||||
#pragma warning restore 612,618
|
||||
taskVersionArray.Wait();
|
||||
|
||||
Version[] versionArray = (Version[])taskVersionArray.Result;
|
||||
@@ -919,15 +929,19 @@ now brown cow?", '"', true);
|
||||
Assert.AreEqual(1, versionArray.Length);
|
||||
Assert.AreEqual(2, versionArray[0].Major);
|
||||
|
||||
#pragma warning disable 612,618
|
||||
Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5");
|
||||
#pragma warning restore 612,618
|
||||
taskInt.Wait();
|
||||
|
||||
Assert.AreEqual(5, taskInt.Result);
|
||||
|
||||
#pragma warning disable 612,618
|
||||
var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings
|
||||
{
|
||||
Converters = { new VersionConverter() }
|
||||
});
|
||||
#pragma warning restore 612,618
|
||||
taskVersion.Wait();
|
||||
|
||||
Assert.AreEqual(2, taskVersion.Result.Major);
|
||||
@@ -935,10 +949,12 @@ now brown cow?", '"', true);
|
||||
Movie p = new Movie();
|
||||
p.Name = "Existing,";
|
||||
|
||||
#pragma warning disable 612,618
|
||||
Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings
|
||||
{
|
||||
Converters = new List<JsonConverter> { new JsonSerializerTest.StringAppenderConverter() }
|
||||
});
|
||||
#pragma warning restore 612,618
|
||||
|
||||
taskVoid.Wait();
|
||||
|
||||
|
||||
@@ -799,8 +799,8 @@ Parameter name: reader",
|
||||
for (int j = 1; j < 1000; j++)
|
||||
{
|
||||
long total = j + i;
|
||||
ExceptionAssert.Throws<OverflowException>(
|
||||
"Arithmetic operation resulted in an overflow.",
|
||||
ExceptionAssert.Throws<JsonReaderException>(
|
||||
"JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 10.",
|
||||
() =>
|
||||
{
|
||||
reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture)));
|
||||
@@ -822,8 +822,8 @@ Parameter name: reader",
|
||||
for (int j = 1; j < 1000; j++)
|
||||
{
|
||||
long total = -j + i;
|
||||
ExceptionAssert.Throws<OverflowException>(
|
||||
"Arithmetic operation resulted in an overflow.",
|
||||
ExceptionAssert.Throws<JsonReaderException>(
|
||||
"JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 11.",
|
||||
() =>
|
||||
{
|
||||
reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture)));
|
||||
@@ -1230,22 +1230,96 @@ bye", reader.Value);
|
||||
Assert.AreEqual(int.MinValue, reader.ReadAsInt32());
|
||||
|
||||
reader = new JsonTextReader(new StringReader(long.MaxValue.ToString()));
|
||||
ExceptionAssert.Throws<OverflowException>("Arithmetic operation resulted in an overflow.", () => reader.ReadAsInt32());
|
||||
ExceptionAssert.Throws<JsonReaderException>("JSON integer 9223372036854775807 is too large or small for an Int32. Path '', line 1, position 19.", () => reader.ReadAsInt32());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
|
||||
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '9999999999999999999999999999999999999999999999999999999999999999999999999999a' is not a valid integer. Path '', line 1, position 77.", () => reader.ReadAsInt32());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("1E-06"));
|
||||
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '1E-06' is not a valid integer. Path '', line 1, position 5.", () => reader.ReadAsInt32());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("1.1"));
|
||||
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '1.1' is not a valid integer. Path '', line 1, position 3.", () => reader.ReadAsInt32());
|
||||
|
||||
reader = new JsonTextReader(new StringReader(""));
|
||||
Assert.AreEqual(null, reader.ReadAsInt32());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-"));
|
||||
ExceptionAssert.Throws<FormatException>("Input string was not in a correct format.", () => reader.ReadAsInt32());
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid integer. Path '', line 1, position 1.", () => reader.ReadAsInt32());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ParseDecimals()
|
||||
{
|
||||
JsonTextReader reader = null;
|
||||
|
||||
reader = new JsonTextReader(new StringReader("1.1"));
|
||||
Assert.AreEqual(1.1m, reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-1.1"));
|
||||
Assert.AreEqual(-1.1m, reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("0.0"));
|
||||
Assert.AreEqual(0.0m, reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-0.0"));
|
||||
Assert.AreEqual(0, reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '9999999999999999999999999999999999999999999999999999999999999999999999999999a' is not a valid decimal. Path '', line 1, position 77.", () => reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
|
||||
reader.FloatParseHandling = Json.FloatParseHandling.Decimal;
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '9999999999999999999999999999999999999999999999999999999999999999999999999999a' is not a valid decimal. Path '', line 1, position 77.", () => reader.Read());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("1E-06"));
|
||||
Assert.AreEqual(0.000001m, reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader(""));
|
||||
Assert.AreEqual(null, reader.ReadAsDecimal());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-"));
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid decimal. Path '', line 1, position 1.", () => reader.ReadAsDecimal());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ParseDoubles()
|
||||
{
|
||||
JsonTextReader reader = null;
|
||||
|
||||
reader = new JsonTextReader(new StringReader("1.1"));
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(typeof(double), reader.ValueType);
|
||||
Assert.AreEqual(1.1d, reader.Value);
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-1.1"));
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(typeof(double), reader.ValueType);
|
||||
Assert.AreEqual(-1.1d, reader.Value);
|
||||
|
||||
reader = new JsonTextReader(new StringReader("0.0"));
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(typeof(double), reader.ValueType);
|
||||
Assert.AreEqual(0.0d, reader.Value);
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-0.0"));
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(typeof(double), reader.ValueType);
|
||||
Assert.AreEqual(-0.0d, reader.Value);
|
||||
|
||||
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '9999999999999999999999999999999999999999999999999999999999999999999999999999a' is not a valid number. Path '', line 1, position 77.", () => reader.Read());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("1E-06"));
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(typeof(double), reader.ValueType);
|
||||
Assert.AreEqual(0.000001d, reader.Value);
|
||||
|
||||
reader = new JsonTextReader(new StringReader(""));
|
||||
Assert.IsFalse(reader.Read());
|
||||
|
||||
reader = new JsonTextReader(new StringReader("-"));
|
||||
ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid number. Path '', line 1, position 1.", () => reader.Read());
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -1975,8 +2049,8 @@ bye", reader.Value);
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
|
||||
|
||||
ExceptionAssert.Throws<FormatException>(
|
||||
"Input string was not in a correct format.",
|
||||
ExceptionAssert.Throws<JsonReaderException>(
|
||||
"Input string '1.1' is not a valid integer. Path 'Name', line 1, position 12.",
|
||||
() => { reader.ReadAsInt32(); });
|
||||
}
|
||||
|
||||
@@ -2448,6 +2522,170 @@ bye", reader.Value);
|
||||
Assert.AreEqual(JsonToken.EndConstructor, reader.TokenType);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingleLineComments()
|
||||
{
|
||||
string json = @"//comment*//*hi*/
|
||||
{//comment
|
||||
Name://comment
|
||||
true//comment after true" + StringUtils.CarriageReturn + @"
|
||||
,//comment after comma" + StringUtils.CarriageReturnLineFeed + @"
|
||||
""ExpiryDate""://comment" + StringUtils.LineFeed + @"
|
||||
new
|
||||
" + StringUtils.LineFeed +
|
||||
@"Date
|
||||
(//comment
|
||||
null//comment
|
||||
),
|
||||
""Price"": 3.99,
|
||||
""Sizes"": //comment
|
||||
[//comment
|
||||
|
||||
""Small""//comment
|
||||
]//comment
|
||||
}//comment
|
||||
//comment 1 ";
|
||||
|
||||
JsonTextReader reader = new JsonTextReader(new StreamReader(new SlowStream(json, new UTF8Encoding(false), 1)));
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual("comment*//*hi*/", reader.Value);
|
||||
Assert.AreEqual(2, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(2, reader.LineNumber);
|
||||
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual(3, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
|
||||
Assert.AreEqual("Name", reader.Value);
|
||||
Assert.AreEqual(3, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual(4, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
|
||||
Assert.AreEqual(true, reader.Value);
|
||||
Assert.AreEqual(4, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual("comment after true", reader.Value);
|
||||
Assert.AreEqual(5, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual("comment after comma", reader.Value);
|
||||
Assert.AreEqual(7, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
|
||||
Assert.AreEqual("ExpiryDate", reader.Value);
|
||||
Assert.AreEqual(8, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual(9, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.StartConstructor, reader.TokenType);
|
||||
Assert.AreEqual(13, reader.LineNumber);
|
||||
Assert.AreEqual("Date", reader.Value);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Null, reader.TokenType);
|
||||
Assert.AreEqual(14, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual(15, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.EndConstructor, reader.TokenType);
|
||||
Assert.AreEqual(15, reader.LineNumber);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
|
||||
Assert.AreEqual("Price", reader.Value);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Float, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
|
||||
Assert.AreEqual("Sizes", reader.Value);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.String, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual("comment ", reader.Value);
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual("comment 1 ", reader.Value);
|
||||
|
||||
Assert.IsFalse(reader.Read());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JustSinglelineComment()
|
||||
{
|
||||
string json = @"//comment";
|
||||
|
||||
JsonTextReader reader = new JsonTextReader(new StreamReader(new SlowStream(json, new UTF8Encoding(false), 1)));
|
||||
|
||||
Assert.IsTrue(reader.Read());
|
||||
Assert.AreEqual(JsonToken.Comment, reader.TokenType);
|
||||
Assert.AreEqual("comment", reader.Value);
|
||||
|
||||
Assert.IsFalse(reader.Read());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ErrorReadingComment()
|
||||
{
|
||||
string json = @"/";
|
||||
|
||||
JsonTextReader reader = new JsonTextReader(new StreamReader(new SlowStream(json, new UTF8Encoding(false), 1)));
|
||||
|
||||
ExceptionAssert.Throws<JsonReaderException>(
|
||||
"Unexpected end while parsing comment. Path '', line 1, position 1.",
|
||||
() => { reader.Read(); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ParseOctalNumber()
|
||||
{
|
||||
|
||||
@@ -1383,6 +1383,54 @@ _____'propertyName': NaN
|
||||
}", stringWriter.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WriteComments()
|
||||
{
|
||||
string json = @"//comment*//*hi*/
|
||||
{//comment
|
||||
Name://comment
|
||||
true//comment after true" + StringUtils.CarriageReturn + @"
|
||||
,//comment after comma" + StringUtils.CarriageReturnLineFeed + @"
|
||||
""ExpiryDate""://comment" + StringUtils.LineFeed + @"
|
||||
new
|
||||
" + StringUtils.LineFeed +
|
||||
@"Constructor
|
||||
(//comment
|
||||
null//comment
|
||||
),
|
||||
""Price"": 3.99,
|
||||
""Sizes"": //comment
|
||||
[//comment
|
||||
|
||||
""Small""//comment
|
||||
]//comment
|
||||
}//comment
|
||||
//comment 1 ";
|
||||
|
||||
JsonTextReader r = new JsonTextReader(new StringReader(json));
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
JsonTextWriter w = new JsonTextWriter(sw);
|
||||
w.Formatting = Formatting.Indented;
|
||||
|
||||
w.WriteToken(r, true);
|
||||
|
||||
Assert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/
|
||||
""Name"": /*comment*/ true/*comment after true*//*comment after comma*/,
|
||||
""ExpiryDate"": /*comment*/ new Constructor(
|
||||
/*comment*/,
|
||||
null
|
||||
/*comment*/
|
||||
),
|
||||
""Price"": 3.99,
|
||||
""Sizes"": /*comment*/ [
|
||||
/*comment*/
|
||||
""Small""
|
||||
/*comment*/
|
||||
]/*comment*/
|
||||
}/*comment *//*comment 1 */", sw.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
public class CustomJsonTextWriter : JsonTextWriter
|
||||
|
||||
@@ -119,6 +119,28 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
|
||||
() => { o.SelectToken("[1]", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateWildcardIndexOnObjectWithError()
|
||||
{
|
||||
JObject o = new JObject(
|
||||
new JProperty("Blah", 1));
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
@"Index * not valid on JObject.",
|
||||
() => { o.SelectToken("[*]", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateSliceOnObjectWithError()
|
||||
{
|
||||
JObject o = new JObject(
|
||||
new JProperty("Blah", 1));
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
@"Array slice is not valid on JObject.",
|
||||
() => { o.SelectToken("[:]", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluatePropertyOnArray()
|
||||
{
|
||||
@@ -128,6 +150,16 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
|
||||
Assert.IsNull(t);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateMultipleResultsError()
|
||||
{
|
||||
JArray a = new JArray(1, 2, 3, 4, 5);
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
@"Path returned multiple tokens.",
|
||||
() => { a.SelectToken("[0, 1]"); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluatePropertyOnArrayWithError()
|
||||
{
|
||||
@@ -138,6 +170,16 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
|
||||
() => { a.SelectToken("BlahBlah", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateNoResultsWithMultipleArrayIndexes()
|
||||
{
|
||||
JArray a = new JArray(1, 2, 3, 4, 5);
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
@"Index 9 outside the bounds of JArray.",
|
||||
() => { a.SelectToken("[9,10]", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateConstructorOutOfBoundsIndxerWithError()
|
||||
{
|
||||
@@ -148,6 +190,14 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
|
||||
() => { c.SelectToken("[1]", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateConstructorOutOfBoundsIndxer()
|
||||
{
|
||||
JConstructor c = new JConstructor("Blah");
|
||||
|
||||
Assert.IsNull(c.SelectToken("[1]"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateMissingPropertyWithError()
|
||||
{
|
||||
@@ -159,6 +209,51 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
|
||||
() => { o.SelectToken("Missing", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateMissingPropertyIndexWithError()
|
||||
{
|
||||
JObject o = new JObject(
|
||||
new JProperty("Blah", 1));
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
"Property 'Missing' does not exist on JObject.",
|
||||
() => { o.SelectToken("['Missing','Missing2']", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateMultiPropertyIndexOnArrayWithError()
|
||||
{
|
||||
JArray a = new JArray(1, 2, 3, 4, 5);
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
"Properties 'Missing', 'Missing2' not valid on JArray.",
|
||||
() => { a.SelectToken("['Missing','Missing2']", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateArraySliceWithError()
|
||||
{
|
||||
JArray a = new JArray(1, 2, 3, 4, 5);
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
"Array slice of 99 to * returned no results.",
|
||||
() => { a.SelectToken("[99:]", true); });
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
"Array slice of 1 to -19 returned no results.",
|
||||
() => { a.SelectToken("[1:-19]", true); });
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
"Array slice of * to -19 returned no results.",
|
||||
() => { a.SelectToken("[:-19]", true); });
|
||||
|
||||
a = new JArray();
|
||||
|
||||
ExceptionAssert.Throws<JsonException>(
|
||||
"Array slice of * to * returned no results.",
|
||||
() => { a.SelectToken("[:]", true); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EvaluateOutOfBoundsIndxer()
|
||||
{
|
||||
|
||||
@@ -131,5 +131,39 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
|
||||
|
||||
Assert.IsFalse(compositeExpression.IsMatch(o3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BooleanExpressionTest()
|
||||
{
|
||||
BooleanQueryExpression e1 = new BooleanQueryExpression
|
||||
{
|
||||
Operator = QueryOperator.LessThan,
|
||||
Value = new JValue(3),
|
||||
Path = new List<PathFilter>
|
||||
{
|
||||
new ArrayIndexFilter()
|
||||
}
|
||||
};
|
||||
|
||||
Assert.IsTrue(e1.IsMatch(new JArray(1, 2, 3, 4, 5)));
|
||||
Assert.IsTrue(e1.IsMatch(new JArray(2, 3, 4, 5)));
|
||||
Assert.IsFalse(e1.IsMatch(new JArray(3, 4, 5)));
|
||||
Assert.IsFalse(e1.IsMatch(new JArray(4, 5)));
|
||||
|
||||
BooleanQueryExpression e2 = new BooleanQueryExpression
|
||||
{
|
||||
Operator = QueryOperator.LessThanOrEquals,
|
||||
Value = new JValue(3),
|
||||
Path = new List<PathFilter>
|
||||
{
|
||||
new ArrayIndexFilter()
|
||||
}
|
||||
};
|
||||
|
||||
Assert.IsTrue(e2.IsMatch(new JArray(1, 2, 3, 4, 5)));
|
||||
Assert.IsTrue(e2.IsMatch(new JArray(2, 3, 4, 5)));
|
||||
Assert.IsTrue(e2.IsMatch(new JArray(3, 4, 5)));
|
||||
Assert.IsFalse(e2.IsMatch(new JArray(4, 5)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,6 @@
|
||||
<Reference Include="System.Web.Extensions">
|
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework>
|
||||
</Reference>
|
||||
<Reference Include="System.Windows" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Xml.Linq">
|
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework>
|
||||
|
||||
@@ -74,5 +74,5 @@ using System.Security;
|
||||
// You can specify all the values or you can default the Revision and Build Numbers
|
||||
// by using the '*' as shown below:
|
||||
|
||||
[assembly: AssemblyVersion("4.5.0.0")]
|
||||
[assembly: AssemblyFileVersion("6.0.1.16816")]
|
||||
[assembly: AssemblyVersion("6.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("6.0.1.17203")]
|
||||
|
||||
@@ -102,6 +102,7 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
}
|
||||
|
||||
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
|
||||
#pragma warning disable 618
|
||||
[Test]
|
||||
public void MemberSearchFlags()
|
||||
{
|
||||
@@ -133,6 +134,7 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
// readonly
|
||||
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
|
||||
}
|
||||
#pragma warning restore 618
|
||||
#endif
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -214,6 +214,7 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
}
|
||||
|
||||
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
|
||||
#pragma warning disable 618
|
||||
[Test]
|
||||
public void SerializeCompilerGeneratedMembers()
|
||||
{
|
||||
@@ -258,6 +259,7 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
""IntProperty"": 2
|
||||
}", includeCompilerGeneratedJson);
|
||||
}
|
||||
#pragma warning restore 618
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -604,6 +604,19 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
public IDictionary<object, object> ExtensionData;
|
||||
}
|
||||
|
||||
public class PublicExtensionDataAttributeTestClassWithNonDefaultConstructor
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public PublicExtensionDataAttributeTestClassWithNonDefaultConstructor(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
|
||||
[JsonExtensionData]
|
||||
public IDictionary<object, object> ExtensionData;
|
||||
}
|
||||
|
||||
public class PublicNoReadExtensionDataAttributeTestClass
|
||||
{
|
||||
public string Name { get; set; }
|
||||
@@ -785,6 +798,34 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
Assert.AreEqual(2m, bizzaroC2.HourlyWage);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializePublicExtensionDataTypeNamdHandlingNonDefaultConstructor()
|
||||
{
|
||||
string json = @"{
|
||||
""$id"": ""1"",
|
||||
""Name"": ""Name!"",
|
||||
""Test"": 1,
|
||||
""Self"": {
|
||||
""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
|
||||
""HourlyWage"": 2.0,
|
||||
""Name"": null,
|
||||
""BirthDate"": ""0001-01-01T00:00:00"",
|
||||
""LastModified"": ""0001-01-01T00:00:00""
|
||||
}
|
||||
}";
|
||||
|
||||
PublicExtensionDataAttributeTestClassWithNonDefaultConstructor c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClassWithNonDefaultConstructor>(json, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Objects
|
||||
});
|
||||
|
||||
Assert.AreEqual("Name!", c2.Name);
|
||||
|
||||
WagePerson bizzaroC2 = (WagePerson)c2.ExtensionData["Self"];
|
||||
|
||||
Assert.AreEqual(2m, bizzaroC2.HourlyWage);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializePublicExtensionDataTypeNamdHandling()
|
||||
{
|
||||
@@ -4257,7 +4298,7 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
#if !NET20
|
||||
dateTimeOffsetText = @"2000-12-20T22:59:59+02:00";
|
||||
#else
|
||||
dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
|
||||
dateTimeOffsetText = @"12/20/2000 22:59:59 +02:00";
|
||||
#endif
|
||||
|
||||
ISerializableTestObject o = new ISerializableTestObject("String!", int.MinValue, dateTimeOffset, person);
|
||||
@@ -7300,7 +7341,7 @@ Parameter name: value",
|
||||
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
MultipleItemsClass foo = serializer.Deserialize<MultipleItemsClass>(reader);
|
||||
|
||||
|
||||
values.Add(foo);
|
||||
}
|
||||
|
||||
@@ -8715,6 +8756,43 @@ Parameter name: value",
|
||||
Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
|
||||
}
|
||||
|
||||
public class ExtensionDataDeserializeWithNonDefaultConstructor
|
||||
{
|
||||
public ExtensionDataDeserializeWithNonDefaultConstructor(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
|
||||
[JsonExtensionData]
|
||||
public IDictionary<string, JToken> _extensionData;
|
||||
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExtensionDataDeserializeWithNonDefaultConstructorTest()
|
||||
{
|
||||
ExtensionDataDeserializeWithNonDefaultConstructor c = new ExtensionDataDeserializeWithNonDefaultConstructor("Name!");
|
||||
c._extensionData = new Dictionary<string, JToken>
|
||||
{
|
||||
{ "Key!", "Value!" }
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
|
||||
|
||||
Assert.AreEqual(@"{
|
||||
""Name"": ""Name!"",
|
||||
""Key!"": ""Value!""
|
||||
}", json);
|
||||
|
||||
var c2 = JsonConvert.DeserializeObject<ExtensionDataDeserializeWithNonDefaultConstructor>(json);
|
||||
|
||||
Assert.AreEqual("Name!", c2.Name);
|
||||
Assert.IsNotNull(c2._extensionData);
|
||||
Assert.AreEqual(1, c2._extensionData.Count);
|
||||
Assert.AreEqual("Value!", (string)c2._extensionData["Key!"]);
|
||||
}
|
||||
|
||||
#if NETFX_CORE
|
||||
[Test]
|
||||
public void SerializeWinRTJsonObject()
|
||||
@@ -9859,6 +9937,20 @@ Parameter name: value",
|
||||
}", s);
|
||||
}
|
||||
#endif
|
||||
|
||||
[Test]
|
||||
public void RoundtripUriOriginalString()
|
||||
{
|
||||
string originalUri = "https://test.com?m=a%2bb";
|
||||
|
||||
Uri uriWithPlus = new Uri(originalUri);
|
||||
|
||||
string jsonWithPlus = JsonConvert.SerializeObject(uriWithPlus);
|
||||
|
||||
Uri uriWithPlus2 = JsonConvert.DeserializeObject<Uri>(jsonWithPlus);
|
||||
|
||||
Assert.AreEqual(originalUri, uriWithPlus2.OriginalString);
|
||||
}
|
||||
}
|
||||
|
||||
public class PersonReference
|
||||
|
||||
@@ -715,6 +715,157 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
@"Unterminated string. Expected delimiter: "". Path '', line 1, position 3.",
|
||||
() => { ErrorTestObject obj = s.Deserialize<ErrorTestObject>(jReader); });
|
||||
}
|
||||
|
||||
public class RootThing
|
||||
{
|
||||
public Something Something { get; set; }
|
||||
}
|
||||
|
||||
public class RootSomethingElse
|
||||
{
|
||||
public SomethingElse SomethingElse { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This could be an object we are passing up in an interface.
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(SomethingConverter))]
|
||||
public class Something
|
||||
{
|
||||
public class SomethingConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Do own stuff.
|
||||
// Then call deserialise for inner object.
|
||||
var innerObject = serializer.Deserialize(reader, typeof(SomethingElse));
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// If we get an error wrap it in something less scary.
|
||||
throw new Exception("An error occurred.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
try
|
||||
{
|
||||
Something s = (Something)value;
|
||||
|
||||
// Do own stuff.
|
||||
// Then call serialise for inner object.
|
||||
serializer.Serialize(writer, s.RootSomethingElse);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// If we get an error wrap it in something less scary.
|
||||
throw new Exception("An error occurred.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public RootSomethingElse RootSomethingElse { get; set; }
|
||||
|
||||
public Something()
|
||||
{
|
||||
this.RootSomethingElse = new RootSomethingElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is an object that is contained in the interface object.
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(SomethingElseConverter))]
|
||||
public class SomethingElse
|
||||
{
|
||||
public class SomethingElseConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeWrappingErrorsAndErrorHandling()
|
||||
{
|
||||
var serialiser = JsonSerializer.Create(new JsonSerializerSettings() { });
|
||||
|
||||
string foo = "{ something: { rootSomethingElse { somethingElse: 0 } } }";
|
||||
var reader = new System.IO.StringReader(foo);
|
||||
|
||||
ExceptionAssert.Throws<Exception>(
|
||||
"An error occurred.",
|
||||
() => { serialiser.Deserialize(reader, typeof(Something)); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializeWrappingErrorsAndErrorHandling()
|
||||
{
|
||||
var serialiser = JsonSerializer.Create(new JsonSerializerSettings() { });
|
||||
|
||||
Something s = new Something
|
||||
{
|
||||
RootSomethingElse = new RootSomethingElse
|
||||
{
|
||||
SomethingElse = new SomethingElse()
|
||||
}
|
||||
};
|
||||
RootThing r = new RootThing
|
||||
{
|
||||
Something = s
|
||||
};
|
||||
|
||||
var writer = new System.IO.StringWriter();
|
||||
|
||||
ExceptionAssert.Throws<Exception>(
|
||||
"An error occurred.",
|
||||
() => { serialiser.Serialize(writer, r); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeserializeRootConverter()
|
||||
{
|
||||
SomethingElse result = JsonConvert.DeserializeObject<SomethingElse>("{}", new JsonSerializerSettings
|
||||
{
|
||||
Error = (o, e) => { e.ErrorContext.Handled = true; }
|
||||
});
|
||||
|
||||
Assert.IsNull(result);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializeRootConverter()
|
||||
{
|
||||
string result = JsonConvert.SerializeObject(new SomethingElse(), new JsonSerializerSettings
|
||||
{
|
||||
Error = (o, e) => { e.ErrorContext.Handled = true; }
|
||||
});
|
||||
|
||||
Assert.AreEqual(string.Empty, result);
|
||||
}
|
||||
}
|
||||
|
||||
internal interface IErrorPerson2
|
||||
|
||||
@@ -54,6 +54,61 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
[TestFixture]
|
||||
public class TypeNameHandlingTests : TestFixtureBase
|
||||
{
|
||||
[Test]
|
||||
public void DictionaryAuto()
|
||||
{
|
||||
Dictionary<string, object> dic = new Dictionary<string, object>
|
||||
{
|
||||
{ "movie", new Movie { Name = "Die Hard"}}
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Auto
|
||||
});
|
||||
|
||||
Assert.AreEqual(@"{
|
||||
""movie"": {
|
||||
""$type"": ""Newtonsoft.Json.Tests.TestObjects.Movie, Newtonsoft.Json.Tests"",
|
||||
""Name"": ""Die Hard"",
|
||||
""Description"": null,
|
||||
""Classification"": null,
|
||||
""Studio"": null,
|
||||
""ReleaseDate"": null,
|
||||
""ReleaseCountries"": null
|
||||
}
|
||||
}", json);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void KeyValuePairAuto()
|
||||
{
|
||||
IList<KeyValuePair<string, object>> dic = new List<KeyValuePair<string, object>>
|
||||
{
|
||||
new KeyValuePair<string, object>("movie", new Movie { Name = "Die Hard"})
|
||||
};
|
||||
|
||||
string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.Auto
|
||||
});
|
||||
|
||||
Assert.AreEqual(@"[
|
||||
{
|
||||
""Key"": ""movie"",
|
||||
""Value"": {
|
||||
""$type"": ""Newtonsoft.Json.Tests.TestObjects.Movie, Newtonsoft.Json.Tests"",
|
||||
""Name"": ""Die Hard"",
|
||||
""Description"": null,
|
||||
""Classification"": null,
|
||||
""Studio"": null,
|
||||
""ReleaseDate"": null,
|
||||
""ReleaseCountries"": null
|
||||
}
|
||||
}
|
||||
]", json);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NestedValueObjects()
|
||||
{
|
||||
@@ -1653,6 +1708,35 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
Assert.AreEqual("string!", ((MyChild)p2.Child).MyProperty);
|
||||
}
|
||||
#endif
|
||||
|
||||
[Test]
|
||||
public void ListOfStackWithFullAssemblyName()
|
||||
{
|
||||
var input = new List<Stack<string>>();
|
||||
|
||||
input.Add(new Stack<string>(new List<string> { "One", "Two", "Three" }));
|
||||
input.Add(new Stack<string>(new List<string> { "Four", "Five", "Six" }));
|
||||
input.Add(new Stack<string>(new List<string> { "Seven", "Eight", "Nine" }));
|
||||
|
||||
string serialized = JsonConvert.SerializeObject(input,
|
||||
Newtonsoft.Json.Formatting.Indented,
|
||||
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormat = FormatterAssemblyStyle.Full } // TypeNameHandling.Auto will work
|
||||
);
|
||||
|
||||
Console.WriteLine(serialized);
|
||||
|
||||
var output = JsonConvert.DeserializeObject<List<Stack<string>>>(serialized,
|
||||
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
|
||||
);
|
||||
|
||||
foreach (var stack in output)
|
||||
{
|
||||
foreach (var value in stack)
|
||||
{
|
||||
Console.WriteLine(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !NETFX_CORE
|
||||
|
||||
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Tests.Serialization
|
||||
#else
|
||||
[JsonIgnore]
|
||||
#endif
|
||||
public string nonSerializedField;
|
||||
public string nonSerializedField;
|
||||
|
||||
public bool Equals(SerializableType other)
|
||||
{
|
||||
|
||||
@@ -2,4 +2,5 @@
|
||||
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_FIELD_ATTRIBUTE_ON_SAME_LINE/@EntryValue">False</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AROUND_MULTIPLICATIVE_OP/@EntryValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LINES/@EntryValue">False</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
|
||||
</wpf:ResourceDictionary>
|
||||
@@ -48,6 +48,10 @@ namespace Newtonsoft.Json.Converters
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
Type t = value.GetType();
|
||||
IList<Type> genericArguments = t.GetGenericArguments();
|
||||
Type keyType = genericArguments[0];
|
||||
Type valueType = genericArguments[1];
|
||||
|
||||
PropertyInfo keyProperty = t.GetProperty(KeyName);
|
||||
PropertyInfo valueProperty = t.GetProperty(ValueName);
|
||||
|
||||
@@ -56,9 +60,9 @@ namespace Newtonsoft.Json.Converters
|
||||
writer.WriteStartObject();
|
||||
|
||||
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
|
||||
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value));
|
||||
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value), keyType);
|
||||
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName);
|
||||
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value));
|
||||
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value), valueType);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
|
||||
@@ -397,7 +397,7 @@ namespace Newtonsoft.Json
|
||||
|
||||
internal static string ToString(Uri value, char quoteChar)
|
||||
{
|
||||
return ToString(value.ToString(), quoteChar);
|
||||
return ToString(value.OriginalString, quoteChar);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -642,6 +642,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("SerializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to serialize JSON asynchronously: Task.Factory.StartNew(() => SerializeObject(value))")]
|
||||
public static Task<string> SerializeObjectAsync(object value)
|
||||
{
|
||||
return SerializeObjectAsync(value, Formatting.None, null);
|
||||
@@ -656,6 +657,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("SerializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to serialize JSON asynchronously: Task.Factory.StartNew(() => SerializeObject(value, formatting))")]
|
||||
public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
|
||||
{
|
||||
return SerializeObjectAsync(value, formatting, null);
|
||||
@@ -672,6 +674,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("SerializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to serialize JSON asynchronously: Task.Factory.StartNew(() => SerializeObject(value, formatting, settings))")]
|
||||
public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
|
||||
{
|
||||
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
|
||||
@@ -819,14 +822,16 @@ namespace Newtonsoft.Json
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(value, "value");
|
||||
|
||||
StringReader sr = new StringReader(value);
|
||||
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
|
||||
|
||||
// by default DeserializeObject should check for additional content
|
||||
if (!jsonSerializer.IsCheckAdditionalContentSet())
|
||||
jsonSerializer.CheckAdditionalContent = true;
|
||||
|
||||
return jsonSerializer.Deserialize(new JsonTextReader(sr), type);
|
||||
using (var reader = new JsonTextReader(new StringReader(value)))
|
||||
{
|
||||
return jsonSerializer.Deserialize(reader, type);
|
||||
}
|
||||
}
|
||||
|
||||
#if !(NET20 || NET35 || PORTABLE40)
|
||||
@@ -839,6 +844,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => DeserializeObject<T>(value))")]
|
||||
public static Task<T> DeserializeObjectAsync<T>(string value)
|
||||
{
|
||||
return DeserializeObjectAsync<T>(value, null);
|
||||
@@ -857,6 +863,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => DeserializeObject<T>(value, settings))")]
|
||||
public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
|
||||
{
|
||||
return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
|
||||
@@ -870,6 +877,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => DeserializeObject(value))")]
|
||||
public static Task<object> DeserializeObjectAsync(string value)
|
||||
{
|
||||
return DeserializeObjectAsync(value, null, null);
|
||||
@@ -888,6 +896,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => DeserializeObject(value, type, settings))")]
|
||||
public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
|
||||
{
|
||||
return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
|
||||
@@ -916,10 +925,9 @@ namespace Newtonsoft.Json
|
||||
/// </param>
|
||||
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
|
||||
{
|
||||
StringReader sr = new StringReader(value);
|
||||
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
|
||||
|
||||
using (JsonReader jsonReader = new JsonTextReader(sr))
|
||||
using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
|
||||
{
|
||||
jsonSerializer.Populate(jsonReader, target);
|
||||
|
||||
@@ -941,6 +949,7 @@ namespace Newtonsoft.Json
|
||||
/// <returns>
|
||||
/// A task that represents the asynchronous populate operation.
|
||||
/// </returns>
|
||||
[ObsoleteAttribute("PopulateObjectAsync is obsolete. Use the Task.Factory.StartNew method to populate an object with JSON values asynchronously: Task.Factory.StartNew(() => PopulateObject(value, target, settings))")]
|
||||
public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings)
|
||||
{
|
||||
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
|
||||
|
||||
@@ -1195,7 +1195,14 @@ namespace Newtonsoft.Json
|
||||
}
|
||||
else
|
||||
{
|
||||
numberValue = ConvertUtils.Int32Parse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
|
||||
int value;
|
||||
ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
|
||||
if (parseResult == ParseResult.Success)
|
||||
numberValue = value;
|
||||
else if (parseResult == ParseResult.Overflow)
|
||||
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
|
||||
else
|
||||
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
|
||||
}
|
||||
|
||||
numberType = JsonToken.Integer;
|
||||
@@ -1222,7 +1229,11 @@ namespace Newtonsoft.Json
|
||||
{
|
||||
string number = _stringReference.ToString();
|
||||
|
||||
numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
|
||||
decimal value;
|
||||
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
|
||||
numberValue = value;
|
||||
else
|
||||
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
|
||||
}
|
||||
|
||||
numberType = JsonToken.Float;
|
||||
@@ -1253,17 +1264,6 @@ namespace Newtonsoft.Json
|
||||
numberValue = value;
|
||||
numberType = JsonToken.Integer;
|
||||
}
|
||||
else if (parseResult == ParseResult.Invalid)
|
||||
{
|
||||
string number = _stringReference.ToString();
|
||||
|
||||
if (_floatParseHandling == FloatParseHandling.Decimal)
|
||||
numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
|
||||
else
|
||||
numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture);
|
||||
|
||||
numberType = JsonToken.Float;
|
||||
}
|
||||
else if (parseResult == ParseResult.Overflow)
|
||||
{
|
||||
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
|
||||
@@ -1271,13 +1271,31 @@ namespace Newtonsoft.Json
|
||||
numberValue = BigInteger.Parse(number, CultureInfo.InvariantCulture);
|
||||
numberType = JsonToken.Integer;
|
||||
#else
|
||||
// todo - validate number was a valid integer to make sure overflow was the reason for failure
|
||||
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
throw JsonReaderException.Create(this, "Unknown error parsing integer.");
|
||||
string number = _stringReference.ToString();
|
||||
|
||||
if (_floatParseHandling == FloatParseHandling.Decimal)
|
||||
{
|
||||
decimal d;
|
||||
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
|
||||
numberValue = d;
|
||||
else
|
||||
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
|
||||
}
|
||||
else
|
||||
{
|
||||
double d;
|
||||
if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
|
||||
numberValue = d;
|
||||
else
|
||||
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
|
||||
}
|
||||
|
||||
numberType = JsonToken.Float;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1292,10 +1310,19 @@ namespace Newtonsoft.Json
|
||||
// should have already parsed / character before reaching this method
|
||||
_charPos++;
|
||||
|
||||
if (!EnsureChars(1, false) || _chars[_charPos] != '*')
|
||||
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
|
||||
if (!EnsureChars(1, false))
|
||||
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
|
||||
|
||||
bool singlelineComment;
|
||||
|
||||
if (_chars[_charPos] == '*')
|
||||
singlelineComment = false;
|
||||
else if (_chars[_charPos] == '/')
|
||||
singlelineComment = true;
|
||||
else
|
||||
_charPos++;
|
||||
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
|
||||
|
||||
_charPos++;
|
||||
|
||||
int initialPosition = _charPos;
|
||||
|
||||
@@ -1309,7 +1336,13 @@ namespace Newtonsoft.Json
|
||||
if (_charsUsed == _charPos)
|
||||
{
|
||||
if (ReadData(true) == 0)
|
||||
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
|
||||
{
|
||||
if (!singlelineComment)
|
||||
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
|
||||
|
||||
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
|
||||
commentFinished = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1319,21 +1352,34 @@ namespace Newtonsoft.Json
|
||||
case '*':
|
||||
_charPos++;
|
||||
|
||||
if (EnsureChars(0, true))
|
||||
if (!singlelineComment)
|
||||
{
|
||||
if (_chars[_charPos] == '/')
|
||||
if (EnsureChars(0, true))
|
||||
{
|
||||
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1);
|
||||
if (_chars[_charPos] == '/')
|
||||
{
|
||||
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1);
|
||||
|
||||
_charPos++;
|
||||
commentFinished = true;
|
||||
_charPos++;
|
||||
commentFinished = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case StringUtils.CarriageReturn:
|
||||
if (singlelineComment)
|
||||
{
|
||||
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
|
||||
commentFinished = true;
|
||||
}
|
||||
ProcessCarriageReturn(true);
|
||||
break;
|
||||
case StringUtils.LineFeed:
|
||||
if (singlelineComment)
|
||||
{
|
||||
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
|
||||
commentFinished = true;
|
||||
}
|
||||
ProcessLineFeed();
|
||||
break;
|
||||
default:
|
||||
@@ -1392,7 +1438,9 @@ namespace Newtonsoft.Json
|
||||
if (!EnsureChars(1, false))
|
||||
return false;
|
||||
|
||||
return (_chars[_charPos + 1] == '*');
|
||||
var nextChart = _chars[_charPos + 1];
|
||||
|
||||
return (nextChart == '*' || nextChart == '/');
|
||||
case ')':
|
||||
if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart)
|
||||
return true;
|
||||
|
||||
@@ -143,14 +143,15 @@ namespace Newtonsoft.Json.Linq
|
||||
/// </example>
|
||||
public new static JArray Parse(string json)
|
||||
{
|
||||
JsonReader reader = new JsonTextReader(new StringReader(json));
|
||||
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
|
||||
{
|
||||
JArray a = Load(reader);
|
||||
|
||||
JArray a = Load(reader);
|
||||
if (reader.Read() && reader.TokenType != JsonToken.Comment)
|
||||
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.Comment)
|
||||
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
|
||||
|
||||
return a;
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -326,14 +326,15 @@ namespace Newtonsoft.Json.Linq
|
||||
/// </example>
|
||||
public new static JObject Parse(string json)
|
||||
{
|
||||
JsonReader reader = new JsonTextReader(new StringReader(json));
|
||||
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
|
||||
{
|
||||
JObject o = Load(reader);
|
||||
|
||||
JObject o = Load(reader);
|
||||
if (reader.Read() && reader.TokenType != JsonToken.Comment)
|
||||
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.Comment)
|
||||
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
|
||||
|
||||
return o;
|
||||
return o;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -208,7 +208,9 @@ namespace Newtonsoft.Json.Linq
|
||||
case JTokenType.Constructor:
|
||||
int index = ((IList<JToken>)current).IndexOf(next);
|
||||
|
||||
sb.Append("[" + index + "]");
|
||||
sb.Append("[");
|
||||
sb.Append(index);
|
||||
sb.Append("]");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1853,14 +1855,15 @@ namespace Newtonsoft.Json.Linq
|
||||
/// <returns>A <see cref="JToken"/> populated from the string that contains JSON.</returns>
|
||||
public static JToken Parse(string json)
|
||||
{
|
||||
JsonReader reader = new JsonTextReader(new StringReader(json));
|
||||
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
|
||||
{
|
||||
JToken t = Load(reader);
|
||||
|
||||
JToken t = Load(reader);
|
||||
if (reader.Read() && reader.TokenType != JsonToken.Comment)
|
||||
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
|
||||
|
||||
if (reader.Read() && reader.TokenType != JsonToken.Comment)
|
||||
throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
|
||||
|
||||
return t;
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1907,59 +1910,61 @@ namespace Newtonsoft.Json.Linq
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects the token that matches the JSON path.
|
||||
/// Selects a <see cref="JToken"/> using a JPath expression. Selects the token that matches the object path.
|
||||
/// </summary>
|
||||
/// <param name="path">
|
||||
/// The object path from the current <see cref="JToken"/> to the <see cref="JToken"/>
|
||||
/// to be returned. This must be a string of property names or array indexes separated
|
||||
/// by periods, such as <code>Tables[0].DefaultView[0].Price</code> in C# or
|
||||
/// <code>Tables(0).DefaultView(0).Price</code> in Visual Basic.
|
||||
/// A <see cref="String"/> that contains a JPath expression.
|
||||
/// </param>
|
||||
/// <returns>The <see cref="JToken"/> that matches the object path or a null reference if no matching token is found.</returns>
|
||||
/// <returns>A <see cref="JToken"/>, or null.</returns>
|
||||
public JToken SelectToken(string path)
|
||||
{
|
||||
return SelectToken(path, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects the token that matches the JSON path.
|
||||
/// Selects a <see cref="JToken"/> using a JPath expression. Selects the token that matches the object path.
|
||||
/// </summary>
|
||||
/// <param name="path">
|
||||
/// The object path from the current <see cref="JToken"/> to the <see cref="JToken"/>
|
||||
/// to be returned. This must be a string of property names or array indexes separated
|
||||
/// by periods, such as <code>Tables[0].DefaultView[0].Price</code> in C# or
|
||||
/// <code>Tables(0).DefaultView(0).Price</code> in Visual Basic.
|
||||
/// A <see cref="String"/> that contains a JPath expression.
|
||||
/// </param>
|
||||
/// <param name="errorWhenNoMatch">A flag to indicate whether an error should be thrown if no token is found.</param>
|
||||
/// <returns>The <see cref="JToken"/> that matches the object path.</returns>
|
||||
/// <param name="errorWhenNoMatch">A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression.</param>
|
||||
/// <returns>A <see cref="JToken"/>.</returns>
|
||||
public JToken SelectToken(string path, bool errorWhenNoMatch)
|
||||
{
|
||||
JPath p = new JPath(path);
|
||||
|
||||
// todo change this to a foreach
|
||||
List<JToken> result = p.Evaluate(this, errorWhenNoMatch).ToList();
|
||||
if (result.Count > 1)
|
||||
throw new Exception("TODO");
|
||||
JToken token = null;
|
||||
foreach (JToken t in p.Evaluate(this, errorWhenNoMatch))
|
||||
{
|
||||
if (token != null)
|
||||
throw new JsonException("Path returned multiple tokens.");
|
||||
|
||||
return result.SingleOrDefault();
|
||||
token = t;
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects tokens that match the JSON path.
|
||||
/// Selects a collection of elements using a JPath expression.
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
/// <param name="path">
|
||||
/// A <see cref="String"/> that contains a JPath expression.
|
||||
/// </param>
|
||||
/// <returns>An <see cref="IEnumerable{JToken}"/> that contains the selected elements.</returns>
|
||||
public IEnumerable<JToken> SelectTokens(string path)
|
||||
{
|
||||
return SelectTokens(path, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects tokens that match the JSON path.
|
||||
/// Selects a collection of elements using a JPath expression.
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="errorWhenNoMatch"></param>
|
||||
/// <returns></returns>
|
||||
/// <param name="path">
|
||||
/// A <see cref="String"/> that contains a JPath expression.
|
||||
/// </param>
|
||||
/// <param name="errorWhenNoMatch">A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression.</param>
|
||||
/// <returns>An <see cref="IEnumerable{JToken}"/> that contains the selected elements.</returns>
|
||||
public IEnumerable<JToken> SelectTokens(string path, bool errorWhenNoMatch)
|
||||
{
|
||||
JPath p = new JPath(path);
|
||||
|
||||
@@ -73,6 +73,15 @@ namespace Newtonsoft.Json.Linq
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
|
||||
/// </summary>
|
||||
/// <param name="value">The value.</param>
|
||||
public JValue(decimal value)
|
||||
: this(value, JTokenType.Float)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
|
||||
/// </summary>
|
||||
@@ -119,6 +128,17 @@ namespace Newtonsoft.Json.Linq
|
||||
{
|
||||
}
|
||||
|
||||
#if !NET20
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
|
||||
/// </summary>
|
||||
/// <param name="value">The value.</param>
|
||||
public JValue(DateTimeOffset value)
|
||||
: this(value, JTokenType.Date)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Linq.JsonPath
|
||||
{
|
||||
@@ -14,33 +16,59 @@ namespace Newtonsoft.Json.Linq.JsonPath
|
||||
if (Step == 0)
|
||||
throw new JsonException("Step cannot be zero.");
|
||||
|
||||
// todo error when no match
|
||||
foreach (JToken t in current)
|
||||
{
|
||||
IList<JToken> sourceCollection = t as IList<JToken> ?? new List<JToken>(t);
|
||||
|
||||
// set defaults for null arguments
|
||||
int stepCount = Step ?? 1;
|
||||
int startIndex = Start ?? ((stepCount > 0) ? 0 : sourceCollection.Count - 1);
|
||||
int stopIndex = End ?? ((stepCount > 0) ? sourceCollection.Count : -1);
|
||||
|
||||
// start from the end of the list if start is negitive
|
||||
if (Start < 0) startIndex = sourceCollection.Count + startIndex;
|
||||
|
||||
// end from the start of the list if stop is negitive
|
||||
if (End < 0) stopIndex = sourceCollection.Count + stopIndex;
|
||||
|
||||
// ensure indexes keep within collection bounds
|
||||
startIndex = Math.Max(startIndex, (stepCount > 0) ? 0 : int.MinValue);
|
||||
startIndex = Math.Min(startIndex, (stepCount > 0) ? sourceCollection.Count : sourceCollection.Count - 1);
|
||||
stopIndex = Math.Max(stopIndex, -1);
|
||||
stopIndex = Math.Min(stopIndex, sourceCollection.Count);
|
||||
|
||||
for (int i = startIndex; (stepCount > 0) ? i < stopIndex : i > stopIndex; i += stepCount)
|
||||
JArray a = t as JArray;
|
||||
if (a != null)
|
||||
{
|
||||
yield return sourceCollection[i];
|
||||
// set defaults for null arguments
|
||||
int stepCount = Step ?? 1;
|
||||
int startIndex = Start ?? ((stepCount > 0) ? 0 : a.Count - 1);
|
||||
int stopIndex = End ?? ((stepCount > 0) ? a.Count : -1);
|
||||
|
||||
// start from the end of the list if start is negitive
|
||||
if (Start < 0) startIndex = a.Count + startIndex;
|
||||
|
||||
// end from the start of the list if stop is negitive
|
||||
if (End < 0) stopIndex = a.Count + stopIndex;
|
||||
|
||||
// ensure indexes keep within collection bounds
|
||||
startIndex = Math.Max(startIndex, (stepCount > 0) ? 0 : int.MinValue);
|
||||
startIndex = Math.Min(startIndex, (stepCount > 0) ? a.Count : a.Count - 1);
|
||||
stopIndex = Math.Max(stopIndex, -1);
|
||||
stopIndex = Math.Min(stopIndex, a.Count);
|
||||
|
||||
bool positiveStep = (stepCount > 0);
|
||||
|
||||
if (IsValid(startIndex, stopIndex, positiveStep))
|
||||
{
|
||||
for (int i = startIndex; IsValid(i, stopIndex, positiveStep); i += stepCount)
|
||||
{
|
||||
yield return a[i];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (errorWhenNoMatch)
|
||||
throw new JsonException("Array slice of {0} to {1} returned no results.".FormatWith(CultureInfo.InvariantCulture,
|
||||
Start != null ? Start.Value.ToString(CultureInfo.InvariantCulture) : "*",
|
||||
End != null ? End.Value.ToString(CultureInfo.InvariantCulture) : "*"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (errorWhenNoMatch)
|
||||
throw new JsonException("Array slice is not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsValid(int index, int stopIndex, bool positiveStep)
|
||||
{
|
||||
if (positiveStep)
|
||||
return (index < stopIndex);
|
||||
|
||||
return (index > stopIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,6 @@ namespace Newtonsoft.Json.Linq.JsonPath
|
||||
}
|
||||
else
|
||||
{
|
||||
// todo - error when no results
|
||||
|
||||
foreach (KeyValuePair<string, JToken> p in o)
|
||||
{
|
||||
yield return p.Value;
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Linq.JsonPath
|
||||
@@ -21,13 +26,16 @@ namespace Newtonsoft.Json.Linq.JsonPath
|
||||
|
||||
if (v != null)
|
||||
yield return v;
|
||||
|
||||
if (errorWhenNoMatch)
|
||||
throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, name));
|
||||
}
|
||||
}
|
||||
//else
|
||||
//{
|
||||
// if (errorWhenNoMatch)
|
||||
// throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, Name ?? "*", t.GetType().Name));
|
||||
//}
|
||||
else
|
||||
{
|
||||
if (errorWhenNoMatch)
|
||||
throw new JsonException("Properties {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", Names.Select(n => "'" + n + "'").ToArray()), t.GetType().Name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,7 +490,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
|
||||
if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1)
|
||||
{
|
||||
double d;
|
||||
if (double.TryParse(numberText, out d))
|
||||
if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
|
||||
return d;
|
||||
else
|
||||
throw new JsonException("Could not read query value.");
|
||||
@@ -498,7 +498,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
|
||||
else
|
||||
{
|
||||
long l;
|
||||
if (long.TryParse(numberText, out l))
|
||||
if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l))
|
||||
return l;
|
||||
else
|
||||
throw new JsonException("Could not read query value.");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RuleSet Name="Newtonsoft.Json.ruleset" ToolsVersion="10.0">
|
||||
<RuleSet Name="Newtonsoft.Json.ruleset" ToolsVersion="12.0">
|
||||
<IncludeAll Action="Warning" />
|
||||
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
|
||||
<Rule Id="CA1000" Action="None" />
|
||||
@@ -67,6 +67,8 @@
|
||||
<Rule Id="CA1301" Action="None" />
|
||||
<Rule Id="CA1302" Action="None" />
|
||||
<Rule Id="CA1303" Action="None" />
|
||||
<Rule Id="CA1304" Action="Error" />
|
||||
<Rule Id="CA1305" Action="Error" />
|
||||
<Rule Id="CA1306" Action="None" />
|
||||
<Rule Id="CA1307" Action="None" />
|
||||
<Rule Id="CA1308" Action="None" />
|
||||
|
||||
@@ -90,6 +90,6 @@ using System.Security;
|
||||
// You can specify all the values or you can default the Revision and Build Numbers
|
||||
// by using the '*' as shown below:
|
||||
|
||||
[assembly: AssemblyVersion("4.5.0.0")]
|
||||
[assembly: AssemblyFileVersion("6.0.1.16816")]
|
||||
[assembly: AssemblyVersion("6.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("6.0.1.17203")]
|
||||
[assembly: CLSCompliant(true)]
|
||||
|
||||
@@ -301,9 +301,10 @@ namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(json, "json");
|
||||
|
||||
JsonReader reader = new JsonTextReader(new StringReader(json));
|
||||
|
||||
return Read(reader, resolver);
|
||||
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
|
||||
{
|
||||
return Read(reader, resolver);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -143,9 +143,10 @@ namespace Newtonsoft.Json.Serialization
|
||||
/// Gets or sets the default members search flags.
|
||||
/// </summary>
|
||||
/// <value>The default members search flags.</value>
|
||||
[ObsoleteAttribute("DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")]
|
||||
public BindingFlags DefaultMembersSearchFlags { get; set; }
|
||||
#else
|
||||
private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public;
|
||||
private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
@@ -194,7 +195,9 @@ namespace Newtonsoft.Json.Serialization
|
||||
public DefaultContractResolver(bool shareCache)
|
||||
{
|
||||
#if !NETFX_CORE
|
||||
#pragma warning disable 618
|
||||
DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance;
|
||||
#pragma warning restore 618
|
||||
#endif
|
||||
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
|
||||
IgnoreSerializableAttribute = true;
|
||||
@@ -280,8 +283,10 @@ namespace Newtonsoft.Json.Serialization
|
||||
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
|
||||
#endif
|
||||
|
||||
#pragma warning disable 618
|
||||
List<MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
|
||||
.Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
|
||||
#pragma warning restore 618
|
||||
|
||||
foreach (MemberInfo member in allMembers)
|
||||
{
|
||||
@@ -1248,8 +1253,10 @@ namespace Newtonsoft.Json.Serialization
|
||||
property.ItemTypeNameHandling = (propertyAttribute != null) ? propertyAttribute._itemTypeNameHandling : null;
|
||||
|
||||
allowNonPublicAccess = false;
|
||||
#pragma warning disable 618
|
||||
if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
|
||||
allowNonPublicAccess = true;
|
||||
#pragma warning restore 618
|
||||
if (propertyAttribute != null)
|
||||
allowNonPublicAccess = true;
|
||||
if (memberSerialization == MemberSerialization.Fields)
|
||||
|
||||
@@ -43,7 +43,7 @@ namespace Newtonsoft.Json.Serialization
|
||||
internal bool Traced { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error.
|
||||
/// Gets the error.
|
||||
/// </summary>
|
||||
/// <value>The error.</value>
|
||||
public Exception Error { get; private set; }
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace Newtonsoft.Json.Serialization
|
||||
if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
|
||||
throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
|
||||
}
|
||||
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
|
||||
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsInstanceOfType(value))
|
||||
{
|
||||
throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
|
||||
}
|
||||
|
||||
@@ -174,6 +174,10 @@ namespace Newtonsoft.Json.Serialization
|
||||
}
|
||||
else
|
||||
{
|
||||
// clear context in case serializer is being used inside a converter
|
||||
// if the converter wraps the error then not clearing the context will cause this error:
|
||||
// "Current error context error is different to requested error."
|
||||
ClearErrorContext();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -1454,7 +1458,8 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
|
||||
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using a non-default constructor '{1}'.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, constructorInfo)), null);
|
||||
|
||||
IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, containerProperty, reader, objectType);
|
||||
IDictionary<string, object> extensionData;
|
||||
IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, containerProperty, reader, objectType, out extensionData);
|
||||
|
||||
IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object)null);
|
||||
IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>();
|
||||
@@ -1489,7 +1494,7 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
JsonProperty property = remainingPropertyValue.Key;
|
||||
object value = remainingPropertyValue.Value;
|
||||
|
||||
if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
|
||||
if (ShouldSetPropertyValue(property, value))
|
||||
{
|
||||
property.ValueProvider.SetValue(createdObject, value);
|
||||
}
|
||||
@@ -1533,6 +1538,14 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
}
|
||||
}
|
||||
|
||||
if (extensionData != null)
|
||||
{
|
||||
foreach (KeyValuePair<string, object> e in extensionData)
|
||||
{
|
||||
contract.ExtensionDataSetter(createdObject, e.Key, e.Value);
|
||||
}
|
||||
}
|
||||
|
||||
EndObject(createdObject, reader, contract, reader.Depth, propertiesPresence);
|
||||
|
||||
OnDeserialized(reader, contract, createdObject);
|
||||
@@ -1552,8 +1565,10 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
return value;
|
||||
}
|
||||
|
||||
private IDictionary<JsonProperty, object> ResolvePropertyAndConstructorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType)
|
||||
private IDictionary<JsonProperty, object> ResolvePropertyAndConstructorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType, out IDictionary<string, object> extensionData)
|
||||
{
|
||||
extensionData = (contract.ExtensionDataSetter != null) ? new Dictionary<string, object>() : null;
|
||||
|
||||
IDictionary<JsonProperty, object> propertyValues = new Dictionary<JsonProperty, object>();
|
||||
bool exit = false;
|
||||
do
|
||||
@@ -1590,10 +1605,7 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
propertyValue = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null);
|
||||
|
||||
propertyValues[property] = propertyValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.Skip();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -1606,7 +1618,15 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
|
||||
if (Serializer._missingMemberHandling == MissingMemberHandling.Error)
|
||||
throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name));
|
||||
}
|
||||
|
||||
if (extensionData != null)
|
||||
{
|
||||
object value = CreateValueInternal(reader, null, null, null, contract, containerProperty, null);
|
||||
extensionData[memberName] = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.Skip();
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -49,6 +49,7 @@ namespace Newtonsoft.Json.Serialization
|
||||
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
|
||||
{
|
||||
private JsonContract _rootContract;
|
||||
private int _rootLevel;
|
||||
private readonly List<object> _serializeStack = new List<object>();
|
||||
private JsonSerializerProxy _internalSerializer;
|
||||
|
||||
@@ -62,10 +63,36 @@ namespace Newtonsoft.Json.Serialization
|
||||
if (jsonWriter == null)
|
||||
throw new ArgumentNullException("jsonWriter");
|
||||
|
||||
if (objectType != null)
|
||||
_rootContract = Serializer._contractResolver.ResolveContract(objectType);
|
||||
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
|
||||
_rootLevel = _serializeStack.Count + 1;
|
||||
|
||||
SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
|
||||
JsonContract contract = GetContractSafe(value);
|
||||
|
||||
try
|
||||
{
|
||||
SerializeValue(jsonWriter, value, contract, null, null, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
|
||||
{
|
||||
HandleError(jsonWriter, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
// clear context in case serializer is being used inside a converter
|
||||
// if the converter wraps the error then not clearing the context will cause this error:
|
||||
// "Current error context error is different to requested error."
|
||||
ClearErrorContext();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// clear root contract to ensure that if level was > 1 then it won't
|
||||
// accidently be used for non root values
|
||||
_rootContract = null;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonSerializerProxy GetInternalSerializer()
|
||||
@@ -848,7 +875,7 @@ To fix this error either change the environment to be fully trusted, change the
|
||||
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
|
||||
return true;
|
||||
}
|
||||
else if (_rootContract != null && _serializeStack.Count == 1)
|
||||
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
|
||||
{
|
||||
if (contract.UnderlyingType != _rootContract.CreatedType)
|
||||
return true;
|
||||
|
||||
@@ -565,10 +565,12 @@ namespace Newtonsoft.Json.Utilities
|
||||
}
|
||||
}
|
||||
|
||||
public static int Int32Parse(char[] chars, int start, int length)
|
||||
public static ParseResult Int32TryParse(char[] chars, int start, int length, out int value)
|
||||
{
|
||||
value = 0;
|
||||
|
||||
if (length == 0)
|
||||
throw new FormatException("Input string was not in a correct format.");
|
||||
return ParseResult.Invalid;
|
||||
|
||||
bool isNegative = (chars[start] == '-');
|
||||
|
||||
@@ -576,13 +578,12 @@ namespace Newtonsoft.Json.Utilities
|
||||
{
|
||||
// text just a negative sign
|
||||
if (length == 1)
|
||||
throw new FormatException("Input string was not in a correct format.");
|
||||
return ParseResult.Invalid;
|
||||
|
||||
start++;
|
||||
length--;
|
||||
}
|
||||
|
||||
int result = 0;
|
||||
int end = start + length;
|
||||
|
||||
for (int i = start; i < end; i++)
|
||||
@@ -590,12 +591,12 @@ namespace Newtonsoft.Json.Utilities
|
||||
int c = chars[i] - '0';
|
||||
|
||||
if (c < 0 || c > 9)
|
||||
throw new FormatException("Input string was not in a correct format.");
|
||||
return ParseResult.Invalid;
|
||||
|
||||
int newValue = (10 * result) - c;
|
||||
int newValue = (10 * value) - c;
|
||||
|
||||
// overflow has caused the number to loop around
|
||||
if (newValue > result)
|
||||
if (newValue > value)
|
||||
{
|
||||
i++;
|
||||
|
||||
@@ -606,13 +607,13 @@ namespace Newtonsoft.Json.Utilities
|
||||
c = chars[i] - '0';
|
||||
|
||||
if (c < 0 || c > 9)
|
||||
throw new FormatException("Input string was not in a correct format.");
|
||||
return ParseResult.Invalid;
|
||||
}
|
||||
|
||||
throw new OverflowException();
|
||||
return ParseResult.Overflow;
|
||||
}
|
||||
|
||||
result = newValue;
|
||||
value = newValue;
|
||||
}
|
||||
|
||||
// go from negative to positive to avoids overflow
|
||||
@@ -620,13 +621,13 @@ namespace Newtonsoft.Json.Utilities
|
||||
if (!isNegative)
|
||||
{
|
||||
// negative integer can be one bigger than positive
|
||||
if (result == int.MinValue)
|
||||
throw new OverflowException();
|
||||
if (value == int.MinValue)
|
||||
return ParseResult.Overflow;
|
||||
|
||||
result = -result;
|
||||
value = -value;
|
||||
}
|
||||
|
||||
return result;
|
||||
return ParseResult.Success;
|
||||
}
|
||||
|
||||
public static ParseResult Int64TryParse(char[] chars, int start, int length, out long value)
|
||||
|
||||
@@ -165,7 +165,7 @@ namespace Newtonsoft.Json.Utilities
|
||||
#if !(NETFX_CORE || PORTABLE)
|
||||
lowerCase = char.ToLower(s[i], CultureInfo.InvariantCulture);
|
||||
#else
|
||||
lowerCase = char.ToLower(s[i]);
|
||||
lowerCase = char.ToLower(s[i]);
|
||||
#endif
|
||||
|
||||
sb.Append(lowerCase);
|
||||
|
||||
Reference in New Issue
Block a user