-6.0.2 merge

This commit is contained in:
James Newton-King
2014-04-03 15:05:18 +13:00
39 changed files with 1127 additions and 171 deletions
@@ -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();
+249 -11
View File
@@ -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)
{