/Imports/Newtonsoft.Json/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs
C# | 9246 lines | 8176 code | 958 blank | 112 comment | 101 complexity | 80400fc04ff1db65c375fbcba080b06e MD5 | raw file
Possible License(s): GPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, Apache-2.0, BSD-3-Clause, CC-BY-SA-3.0
Large files files are truncated, but you can click here to view the full file
- #region License
- // Copyright (c) 2007 James Newton-King
- //
- // Permission is hereby granted, free of charge, to any person
- // obtaining a copy of this software and associated documentation
- // files (the "Software"), to deal in the Software without
- // restriction, including without limitation the rights to use,
- // copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the
- // Software is furnished to do so, subject to the following
- // conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- // OTHER DEALINGS IN THE SOFTWARE.
- #endregion
-
- using System;
- using System.ComponentModel;
- #if !(NET35 || NET20)
- using System.Collections.Concurrent;
- #endif
- using System.Collections.Generic;
- #if !(NET20 || NET35 || PORTABLE || DNXCORE50)
- using System.Numerics;
- #endif
- #if !(NET20 || NETFX_CORE || DNXCORE50)
- using System.ComponentModel.DataAnnotations;
- using System.Configuration;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization.Formatters;
- using System.Threading;
- using System.Web.Script.Serialization;
- #endif
- using System.Text;
- using System.Text.RegularExpressions;
- #if NETFX_CORE
- using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
- using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
- using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
- #elif DNXCORE50
- using Xunit;
- using Test = Xunit.FactAttribute;
- using Assert = Newtonsoft.Json.Tests.XUnitAssert;
- #else
- using NUnit.Framework;
- #endif
- using Newtonsoft.Json;
- using System.IO;
- using System.Collections;
- using System.Xml;
- using System.Xml.Serialization;
- using System.Collections.ObjectModel;
- using Newtonsoft.Json.Bson;
- using Newtonsoft.Json.Linq;
- using Newtonsoft.Json.Converters;
- #if !NET20
- using System.Runtime.Serialization.Json;
- #endif
- using Newtonsoft.Json.Serialization;
- using Newtonsoft.Json.Tests.Linq;
- using Newtonsoft.Json.Tests.TestObjects;
- using System.Runtime.Serialization;
- using System.Globalization;
- using Newtonsoft.Json.Utilities;
- using System.Reflection;
- #if !NET20
- using System.Xml.Linq;
- using System.Collections.Specialized;
- using System.Linq.Expressions;
- #endif
- #if !(NET35 || NET20)
- using System.Dynamic;
- #endif
- #if NET20
- using Newtonsoft.Json.Utilities.LinqBridge;
- #else
- using System.Linq;
- #endif
- #if !(NETFX_CORE || DNXCORE50)
- using System.Drawing;
- using System.Diagnostics;
- #endif
-
- namespace Newtonsoft.Json.Tests.Serialization
- {
- [TestFixture]
- public class JsonSerializerTest : TestFixtureBase
- {
- public class DictionaryKeyContractResolver : DefaultContractResolver
- {
- protected override string ResolveDictionaryKey(string dictionaryKey)
- {
- return dictionaryKey;
- }
-
- protected override string ResolvePropertyName(string propertyName)
- {
- return propertyName.ToUpper(CultureInfo.InvariantCulture);
- }
- }
-
- [Test]
- public void DictionaryKeyContractResolverTest()
- {
- var person = new
- {
- Name = "James",
- Age = 1,
- RoleNames = new Dictionary<string, bool>
- {
- { "IsAdmin", true },
- { "IsModerator", false }
- }
- };
-
- string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
- {
- ContractResolver = new DictionaryKeyContractResolver()
- });
-
- Assert.AreEqual(@"{
- ""NAME"": ""James"",
- ""AGE"": 1,
- ""ROLENAMES"": {
- ""IsAdmin"": true,
- ""IsModerator"": false
- }
- }", json);
- }
-
- [Test]
- public void IncompleteContainers()
- {
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<IList<int>>("[1,"),
- "Unexpected end when deserializing array. Path '[0]', line 1, position 3.");
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<IList<int>>("[1"),
- "Unexpected end when deserializing array. Path '[0]', line 1, position 2.");
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1,"),
- "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<IDictionary<string, int>>("{'key':1"),
- "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1,"),
- "Unexpected end when deserializing object. Path 'key', line 1, position 9.");
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<IncompleteTestClass>("{'key':1"),
- "Unexpected end when deserializing object. Path 'key', line 1, position 8.");
- }
-
- public class IncompleteTestClass
- {
- public int Key { get; set; }
- }
-
- #if !NET20
- public enum EnumA
- {
- [EnumMember(Value = "value_a")]
- ValueA
- }
-
- [Test]
- public void DeserializeEnumsByName()
- {
- var e1 = JsonConvert.DeserializeObject<EnumA>("'ValueA'");
- Assert.AreEqual(EnumA.ValueA, e1);
-
- var e2 = JsonConvert.DeserializeObject<EnumA>("'value_a'", new StringEnumConverter());
- Assert.AreEqual(EnumA.ValueA, e2);
- }
- #endif
-
- public class RequiredPropertyTestClass
- {
- [JsonRequired]
- internal string Name { get; set; }
- }
-
- [Test]
- public void RequiredPropertyTest()
- {
- RequiredPropertyTestClass c1 = new RequiredPropertyTestClass();
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.SerializeObject(c1),
- "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
-
- RequiredPropertyTestClass c2 = new RequiredPropertyTestClass
- {
- Name = "Name!"
- };
-
- string json = JsonConvert.SerializeObject(c2);
-
- Assert.AreEqual(@"{""Name"":""Name!""}", json);
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{}"),
- "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":null}"),
- "Required property 'Name' expects a value but got null. Path '', line 1, position 13.");
-
- RequiredPropertyTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyTestClass>(@"{""Name"":""Name!""}");
-
- Assert.AreEqual("Name!", c3.Name);
- }
-
- public class RequiredPropertyConstructorTestClass
- {
- public RequiredPropertyConstructorTestClass(string name)
- {
- Name = name;
- }
-
- [JsonRequired]
- internal string Name { get; set; }
- }
-
- [Test]
- public void RequiredPropertyConstructorTest()
- {
- RequiredPropertyConstructorTestClass c1 = new RequiredPropertyConstructorTestClass(null);
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.SerializeObject(c1),
- "Cannot write a null value for property 'Name'. Property requires a value. Path ''.");
-
- RequiredPropertyConstructorTestClass c2 = new RequiredPropertyConstructorTestClass("Name!");
-
- string json = JsonConvert.SerializeObject(c2);
-
- Assert.AreEqual(@"{""Name"":""Name!""}", json);
-
- ExceptionAssert.Throws<JsonSerializationException>(
- () => JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{}"),
- "Required property 'Name' not found in JSON. Path '', line 1, position 2.");
-
- RequiredPropertyConstructorTestClass c3 = JsonConvert.DeserializeObject<RequiredPropertyConstructorTestClass>(@"{""Name"":""Name!""}");
-
- Assert.AreEqual("Name!", c3.Name);
- }
-
- public class IgnoredPropertiesTestClass
- {
- [JsonIgnore]
- public Version IgnoredProperty { get; set; }
- [JsonIgnore]
- public List<Version> IgnoredList { get; set; }
- [JsonIgnore]
- public Dictionary<string, Version> IgnoredDictionary { get; set; }
- [JsonProperty(Required = Required.Always)]
- public string Name { get; set; }
- }
-
- public class IgnoredPropertiesContractResolver : DefaultContractResolver
- {
- public override JsonContract ResolveContract(Type type)
- {
- if (type == typeof(Version))
- throw new Exception("Error!");
-
- return base.ResolveContract(type);
- }
- }
-
- [Test]
- public void NeverResolveIgnoredPropertyTypes()
- {
- Version v = new Version(1, 2, 3, 4);
-
- IgnoredPropertiesTestClass c1 = new IgnoredPropertiesTestClass
- {
- IgnoredProperty = v,
- IgnoredList = new List<Version>
- {
- v
- },
- IgnoredDictionary = new Dictionary<string, Version>
- {
- { "Value", v }
- },
- Name = "Name!"
- };
-
- string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
- {
- ContractResolver = new IgnoredPropertiesContractResolver()
- });
-
- Assert.AreEqual(@"{
- ""Name"": ""Name!""
- }", json);
-
- string deserializeJson = @"{
- ""IgnoredList"": [
- {
- ""Major"": 1,
- ""Minor"": 2,
- ""Build"": 3,
- ""Revision"": 4,
- ""MajorRevision"": 0,
- ""MinorRevision"": 4
- }
- ],
- ""IgnoredDictionary"": {
- ""Value"": {
- ""Major"": 1,
- ""Minor"": 2,
- ""Build"": 3,
- ""Revision"": 4,
- ""MajorRevision"": 0,
- ""MinorRevision"": 4
- }
- },
- ""Name"": ""Name!""
- }";
-
- IgnoredPropertiesTestClass c2 = JsonConvert.DeserializeObject<IgnoredPropertiesTestClass>(deserializeJson, new JsonSerializerSettings
- {
- ContractResolver = new IgnoredPropertiesContractResolver()
- });
-
- Assert.AreEqual("Name!", c2.Name);
- }
-
- #if !(NETFX_CORE || DNXCORE50 || NET20)
- [MetadataType(typeof(CustomerValidation))]
- public partial class CustomerWithMetadataType
- {
- public System.Guid UpdatedBy_Id { get; set; }
-
- public class CustomerValidation
- {
- [JsonIgnore]
- public System.Guid UpdatedBy_Id { get; set; }
- }
- }
-
- [Test]
- public void SerializeMetadataType()
- {
- CustomerWithMetadataType c = new CustomerWithMetadataType();
- c.UpdatedBy_Id = Guid.NewGuid();
-
- string json = JsonConvert.SerializeObject(c);
-
- Assert.AreEqual("{}", json);
-
- CustomerWithMetadataType c2 = JsonConvert.DeserializeObject<CustomerWithMetadataType>("{'UpdatedBy_Id':'F6E0666D-13C7-4745-B486-800812C8F6DE'}");
-
- Assert.AreEqual(Guid.Empty, c2.UpdatedBy_Id);
- }
-
- [Serializable]
- public partial class FaqItem
- {
- public FaqItem()
- {
- this.Sections = new HashSet<FaqSection>();
- }
-
- public int FaqId { get; set; }
- public string Name { get; set; }
- public bool IsDeleted { get; set; }
-
- public virtual ICollection<FaqSection> Sections { get; set; }
- }
-
- [MetadataType(typeof(FaqItemMetadata))]
- partial class FaqItem
- {
- [JsonProperty("FullSectionsProp")]
- public ICollection<FaqSection> FullSections
- {
- get { return Sections; }
- }
- }
-
- public class FaqItemMetadata
- {
- [JsonIgnore]
- public virtual ICollection<FaqSection> Sections { get; set; }
- }
-
- public class FaqSection
- {
- }
-
- public class FaqItemProxy : FaqItem
- {
- public bool IsProxy { get; set; }
-
- public override ICollection<FaqSection> Sections
- {
- get { return base.Sections; }
- set { base.Sections = value; }
- }
- }
-
- [Test]
- public void SerializeMetadataType2()
- {
- FaqItem c = new FaqItem();
- c.FaqId = 1;
- c.Sections.Add(new FaqSection());
-
- string json = JsonConvert.SerializeObject(c, Formatting.Indented);
-
- StringAssert.AreEqual(@"{
- ""FaqId"": 1,
- ""Name"": null,
- ""IsDeleted"": false,
- ""FullSectionsProp"": [
- {}
- ]
- }", json);
-
- FaqItem c2 = JsonConvert.DeserializeObject<FaqItem>(json);
-
- Assert.AreEqual(1, c2.FaqId);
- Assert.AreEqual(1, c2.Sections.Count);
- }
-
- [Test]
- public void SerializeMetadataTypeInheritance()
- {
- FaqItemProxy c = new FaqItemProxy();
- c.FaqId = 1;
- c.Sections.Add(new FaqSection());
- c.IsProxy = true;
-
- string json = JsonConvert.SerializeObject(c, Formatting.Indented);
-
- StringAssert.AreEqual(@"{
- ""IsProxy"": true,
- ""FaqId"": 1,
- ""Name"": null,
- ""IsDeleted"": false,
- ""FullSectionsProp"": [
- {}
- ]
- }", json);
-
- FaqItemProxy c2 = JsonConvert.DeserializeObject<FaqItemProxy>(json);
-
- Assert.AreEqual(1, c2.FaqId);
- Assert.AreEqual(1, c2.Sections.Count);
- }
- #endif
-
- public class NullTestClass
- {
- public JObject Value1 { get; set; }
- public JValue Value2 { get; set; }
- public JRaw Value3 { get; set; }
- public JToken Value4 { get; set; }
- public object Value5 { get; set; }
- }
-
- [Test]
- public void DeserializeNullToJTokenProperty()
- {
- NullTestClass otc = JsonConvert.DeserializeObject<NullTestClass>(@"{
- ""Value1"": null,
- ""Value2"": null,
- ""Value3"": null,
- ""Value4"": null,
- ""Value5"": null
- }");
- Assert.IsNull(otc.Value1);
- Assert.AreEqual(JTokenType.Null, otc.Value2.Type);
- Assert.AreEqual(JTokenType.Raw, otc.Value3.Type);
- Assert.AreEqual(JTokenType.Null, otc.Value4.Type);
- Assert.IsNull(otc.Value5);
- }
-
- public class Link
- {
- /// <summary>
- /// The unique identifier.
- /// </summary>
- public int Id;
-
- /// <summary>
- /// The parent information identifier.
- /// </summary>
- public int ParentId;
-
- /// <summary>
- /// The child information identifier.
- /// </summary>
- public int ChildId;
- }
-
- #if !(NET20 || NET35 || PORTABLE40 || PORTABLE || DNXCORE50)
- [Test]
- public void ReadIntegerWithError()
- {
- string json = @"{
- ParentId: 1,
- ChildId: 333333333333333333333333333333333333333
- }";
-
- Link l = JsonConvert.DeserializeObject<Link>(json, new JsonSerializerSettings
- {
- Error = (s, a) => a.ErrorContext.Handled = true
- });
-
- Assert.AreEqual(0, l.ChildId);
- }
- #endif
-
- #if !(NET20 || NET35)
- [Test]
- public void DeserializeObservableCollection()
- {
- ObservableCollection<string> s = JsonConvert.DeserializeObject<ObservableCollection<string>>("['1','2']");
- Assert.AreEqual(2, s.Count);
- Assert.AreEqual("1", s[0]);
- Assert.AreEqual("2", s[1]);
- }
- #endif
-
- #if !NET20
- [Test]
- public void PopulateResetSettings()
- {
- JsonTextReader reader = new JsonTextReader(new StringReader(@"[""2000-01-01T01:01:01+00:00""]"));
- Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
-
- JsonSerializer serializer = new JsonSerializer();
- serializer.DateParseHandling = DateParseHandling.DateTimeOffset;
-
- IList<object> l = new List<object>();
- serializer.Populate(reader, l);
-
- Assert.AreEqual(typeof(DateTimeOffset), l[0].GetType());
- Assert.AreEqual(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero), l[0]);
-
- Assert.AreEqual(DateParseHandling.DateTime, reader.DateParseHandling);
- }
- #endif
-
- public class BaseClass
- {
- internal bool IsTransient { get; set; }
- }
-
- public class ChildClass : BaseClass
- {
- public new bool IsTransient { get; set; }
- }
-
- [Test]
- public void NewProperty()
- {
- Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClass { IsTransient = true }));
-
- var childClass = JsonConvert.DeserializeObject<ChildClass>(@"{""IsTransient"":true}");
- Assert.AreEqual(true, childClass.IsTransient);
- }
-
- public class BaseClassVirtual
- {
- internal virtual bool IsTransient { get; set; }
- }
-
- public class ChildClassVirtual : BaseClassVirtual
- {
- public new virtual bool IsTransient { get; set; }
- }
-
- [Test]
- public void NewPropertyVirtual()
- {
- Assert.AreEqual(@"{""IsTransient"":true}", JsonConvert.SerializeObject(new ChildClassVirtual { IsTransient = true }));
-
- var childClass = JsonConvert.DeserializeObject<ChildClassVirtual>(@"{""IsTransient"":true}");
- Assert.AreEqual(true, childClass.IsTransient);
- }
-
- public class ResponseWithNewGenericProperty<T> : SimpleResponse
- {
- public new T Data { get; set; }
- }
-
- public class ResponseWithNewGenericPropertyVirtual<T> : SimpleResponse
- {
- public new virtual T Data { get; set; }
- }
-
- public class ResponseWithNewGenericPropertyOverride<T> : ResponseWithNewGenericPropertyVirtual<T>
- {
- public override T Data { get; set; }
- }
-
- public abstract class SimpleResponse
- {
- public string Result { get; set; }
- public string Message { get; set; }
- public object Data { get; set; }
-
- protected SimpleResponse()
- {
-
- }
-
- protected SimpleResponse(string message)
- {
- Message = message;
- }
- }
-
- [Test]
- public void CanSerializeWithBuiltInTypeAsGenericArgument()
- {
- var input = new ResponseWithNewGenericProperty<int>()
- {
- Message = "Trying out integer as type parameter",
- Data = 25,
- Result = "This should be fine"
- };
-
- var json = JsonConvert.SerializeObject(input);
- var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<int>>(json);
-
- Assert.AreEqual(input.Data, deserialized.Data);
- Assert.AreEqual(input.Message, deserialized.Message);
- Assert.AreEqual(input.Result, deserialized.Result);
- }
-
- [Test]
- public void CanSerializeWithBuiltInTypeAsGenericArgumentVirtual()
- {
- var input = new ResponseWithNewGenericPropertyVirtual<int>()
- {
- Message = "Trying out integer as type parameter",
- Data = 25,
- Result = "This should be fine"
- };
-
- var json = JsonConvert.SerializeObject(input);
- var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyVirtual<int>>(json);
-
- Assert.AreEqual(input.Data, deserialized.Data);
- Assert.AreEqual(input.Message, deserialized.Message);
- Assert.AreEqual(input.Result, deserialized.Result);
- }
-
- [Test]
- public void CanSerializeWithBuiltInTypeAsGenericArgumentOverride()
- {
- var input = new ResponseWithNewGenericPropertyOverride<int>()
- {
- Message = "Trying out integer as type parameter",
- Data = 25,
- Result = "This should be fine"
- };
-
- var json = JsonConvert.SerializeObject(input);
- var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericPropertyOverride<int>>(json);
-
- Assert.AreEqual(input.Data, deserialized.Data);
- Assert.AreEqual(input.Message, deserialized.Message);
- Assert.AreEqual(input.Result, deserialized.Result);
- }
-
- [Test]
- public void CanSerializedWithGenericClosedTypeAsArgument()
- {
- var input = new ResponseWithNewGenericProperty<List<int>>()
- {
- Message = "More complex case - generic list of int",
- Data = Enumerable.Range(50, 70).ToList(),
- Result = "This should be fine too"
- };
-
- var json = JsonConvert.SerializeObject(input);
- var deserialized = JsonConvert.DeserializeObject<ResponseWithNewGenericProperty<List<int>>>(json);
-
- CollectionAssert.AreEqual(input.Data, deserialized.Data);
- Assert.AreEqual(input.Message, deserialized.Message);
- Assert.AreEqual(input.Result, deserialized.Result);
- }
-
- [Test]
- public void DeserializeJObjectWithComments()
- {
- string json = @"/* Test */
- {
- /*Test*/""A"":/* Test */true/* Test */,
- /* Test */""B"":/* Test */false/* Test */,
- /* Test */""C"":/* Test */[
- /* Test */
- 1/* Test */
- ]/* Test */
- }
- /* Test */";
- JObject o = (JObject)JsonConvert.DeserializeObject(json);
- Assert.AreEqual(3, o.Count);
- Assert.AreEqual(true, (bool)o["A"]);
- Assert.AreEqual(false, (bool)o["B"]);
- Assert.AreEqual(3, o["C"].Count());
- Assert.AreEqual(JTokenType.Comment, o["C"][0].Type);
- Assert.AreEqual(1, (int)o["C"][1]);
- Assert.AreEqual(JTokenType.Comment, o["C"][2].Type);
- Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
-
- json = @"{/* Test */}";
- o = (JObject)JsonConvert.DeserializeObject(json);
- Assert.AreEqual(0, o.Count);
- Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
-
- json = @"{""A"": true/* Test */}";
- o = (JObject)JsonConvert.DeserializeObject(json);
- Assert.AreEqual(1, o.Count);
- Assert.AreEqual(true, (bool)o["A"]);
- Assert.IsTrue(JToken.DeepEquals(o, JObject.Parse(json)));
- }
-
- public class CommentTestObject
- {
- public bool? A { get; set; }
- }
-
- [Test]
- public void DeserializeCommentTestObjectWithComments()
- {
- CommentTestObject o = JsonConvert.DeserializeObject<CommentTestObject>(@"{/* Test */}");
- Assert.AreEqual(null, o.A);
-
- o = JsonConvert.DeserializeObject<CommentTestObject>(@"{""A"": true/* Test */}");
- Assert.AreEqual(true, o.A);
- }
-
- [Test]
- public void JsonSerializerProperties()
- {
- JsonSerializer serializer = new JsonSerializer();
-
- DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
- serializer.Binder = customBinder;
- Assert.AreEqual(customBinder, serializer.Binder);
-
- serializer.CheckAdditionalContent = true;
- Assert.AreEqual(true, serializer.CheckAdditionalContent);
-
- serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
- Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling);
-
- #if !(NETFX_CORE || DNXCORE50)
- serializer.Context = new StreamingContext(StreamingContextStates.Other);
- Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context);
- #endif
-
- CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
- serializer.ContractResolver = resolver;
- Assert.AreEqual(resolver, serializer.ContractResolver);
-
- serializer.Converters.Add(new StringEnumConverter());
- Assert.AreEqual(1, serializer.Converters.Count);
-
- serializer.Culture = new CultureInfo("en-nz");
- Assert.AreEqual("en-NZ", serializer.Culture.ToString());
-
- serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
- Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializer.DateFormatHandling);
-
- serializer.DateFormatString = "yyyy";
- Assert.AreEqual("yyyy", serializer.DateFormatString);
-
- serializer.DateParseHandling = DateParseHandling.None;
- Assert.AreEqual(DateParseHandling.None, serializer.DateParseHandling);
-
- serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- Assert.AreEqual(DateTimeZoneHandling.Utc, serializer.DateTimeZoneHandling);
-
- serializer.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
- Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializer.DefaultValueHandling);
-
- serializer.FloatFormatHandling = FloatFormatHandling.Symbol;
- Assert.AreEqual(FloatFormatHandling.Symbol, serializer.FloatFormatHandling);
-
- serializer.FloatParseHandling = FloatParseHandling.Decimal;
- Assert.AreEqual(FloatParseHandling.Decimal, serializer.FloatParseHandling);
-
- serializer.Formatting = Formatting.Indented;
- Assert.AreEqual(Formatting.Indented, serializer.Formatting);
-
- serializer.MaxDepth = 9001;
- Assert.AreEqual(9001, serializer.MaxDepth);
-
- serializer.MissingMemberHandling = MissingMemberHandling.Error;
- Assert.AreEqual(MissingMemberHandling.Error, serializer.MissingMemberHandling);
-
- serializer.NullValueHandling = NullValueHandling.Ignore;
- Assert.AreEqual(NullValueHandling.Ignore, serializer.NullValueHandling);
-
- serializer.ObjectCreationHandling = ObjectCreationHandling.Replace;
- Assert.AreEqual(ObjectCreationHandling.Replace, serializer.ObjectCreationHandling);
-
- serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
- Assert.AreEqual(PreserveReferencesHandling.All, serializer.PreserveReferencesHandling);
-
- serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- Assert.AreEqual(ReferenceLoopHandling.Ignore, serializer.ReferenceLoopHandling);
-
- IdReferenceResolver referenceResolver = new IdReferenceResolver();
- serializer.ReferenceResolver = referenceResolver;
- Assert.AreEqual(referenceResolver, serializer.ReferenceResolver);
-
- serializer.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
- Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializer.StringEscapeHandling);
-
- MemoryTraceWriter traceWriter = new MemoryTraceWriter();
- serializer.TraceWriter = traceWriter;
- Assert.AreEqual(traceWriter, serializer.TraceWriter);
-
- #if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20 || DNXCORE50)
- serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
- Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat);
- #endif
-
- serializer.TypeNameHandling = TypeNameHandling.All;
- Assert.AreEqual(TypeNameHandling.All, serializer.TypeNameHandling);
- }
-
- [Test]
- public void JsonSerializerSettingsProperties()
- {
- JsonSerializerSettings settings = new JsonSerializerSettings();
-
- DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
- settings.Binder = customBinder;
- Assert.AreEqual(customBinder, settings.Binder);
-
- settings.CheckAdditionalContent = true;
- Assert.AreEqual(true, settings.CheckAdditionalContent);
-
- settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
- Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling);
-
- #if !(NETFX_CORE || DNXCORE50)
- settings.Context = new StreamingContext(StreamingContextStates.Other);
- Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context);
- #endif
-
- CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
- settings.ContractResolver = resolver;
- Assert.AreEqual(resolver, settings.ContractResolver);
-
- settings.Converters.Add(new StringEnumConverter());
- Assert.AreEqual(1, settings.Converters.Count);
-
- settings.Culture = new CultureInfo("en-nz");
- Assert.AreEqual("en-NZ", settings.Culture.ToString());
-
- settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
- Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, settings.DateFormatHandling);
-
- settings.DateFormatString = "yyyy";
- Assert.AreEqual("yyyy", settings.DateFormatString);
-
- settings.DateParseHandling = DateParseHandling.None;
- Assert.AreEqual(DateParseHandling.None, settings.DateParseHandling);
-
- settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- Assert.AreEqual(DateTimeZoneHandling.Utc, settings.DateTimeZoneHandling);
-
- settings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
- Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, settings.DefaultValueHandling);
-
- settings.FloatFormatHandling = FloatFormatHandling.Symbol;
- Assert.AreEqual(FloatFormatHandling.Symbol, settings.FloatFormatHandling);
-
- settings.FloatParseHandling = FloatParseHandling.Decimal;
- Assert.AreEqual(FloatParseHandling.Decimal, settings.FloatParseHandling);
-
- settings.Formatting = Formatting.Indented;
- Assert.AreEqual(Formatting.Indented, settings.Formatting);
-
- settings.MaxDepth = 9001;
- Assert.AreEqual(9001, settings.MaxDepth);
-
- settings.MissingMemberHandling = MissingMemberHandling.Error;
- Assert.AreEqual(MissingMemberHandling.Error, settings.MissingMemberHandling);
-
- settings.NullValueHandling = NullValueHandling.Ignore;
- Assert.AreEqual(NullValueHandling.Ignore, settings.NullValueHandling);
-
- settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
- Assert.AreEqual(ObjectCreationHandling.Replace, settings.ObjectCreationHandling);
-
- settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
- Assert.AreEqual(PreserveReferencesHandling.All, settings.PreserveReferencesHandling);
-
- settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- Assert.AreEqual(ReferenceLoopHandling.Ignore, settings.ReferenceLoopHandling);
-
- IdReferenceResolver referenceResolver = new IdReferenceResolver();
- #pragma warning disable 618
- settings.ReferenceResolver = referenceResolver;
- Assert.AreEqual(referenceResolver, settings.ReferenceResolver);
- #pragma warning restore 618
- Assert.AreEqual(referenceResolver, settings.ReferenceResolverProvider());
-
- settings.ReferenceResolverProvider = () => referenceResolver;
- Assert.AreEqual(referenceResolver, settings.ReferenceResolverProvider());
-
- settings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
- Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, settings.StringEscapeHandling);
-
- MemoryTraceWriter traceWriter = new MemoryTraceWriter();
- settings.TraceWriter = traceWriter;
- Assert.AreEqual(traceWriter, settings.TraceWriter);
-
- #if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20 || DNXCORE50)
- settings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
- Assert.AreEqual(FormatterAssemblyStyle.Full, settings.TypeNameAssemblyFormat);
- #endif
-
- settings.TypeNameHandling = TypeNameHandling.All;
- Assert.AreEqual(TypeNameHandling.All, settings.TypeNameHandling);
- }
-
- [Test]
- public void JsonSerializerProxyProperties()
- {
- JsonSerializerProxy serializerProxy = new JsonSerializerProxy(new JsonSerializerInternalReader(new JsonSerializer()));
-
- DefaultSerializationBinder customBinder = new DefaultSerializationBinder();
- serializerProxy.Binder = customBinder;
- Assert.AreEqual(customBinder, serializerProxy.Binder);
-
- serializerProxy.CheckAdditionalContent = true;
- Assert.AreEqual(true, serializerProxy.CheckAdditionalContent);
-
- serializerProxy.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
- Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializerProxy.ConstructorHandling);
-
- #if !(NETFX_CORE || DNXCORE50)
- serializerProxy.Context = new StreamingContext(StreamingContextStates.Other);
- Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializerProxy.Context);
- #endif
-
- CamelCasePropertyNamesContractResolver resolver = new CamelCasePropertyNamesContractResolver();
- serializerProxy.ContractResolver = resolver;
- Assert.AreEqual(resolver, serializerProxy.ContractResolver);
-
- serializerProxy.Converters.Add(new StringEnumConverter());
- Assert.AreEqual(1, serializerProxy.Converters.Count);
-
- serializerProxy.Culture = new CultureInfo("en-nz");
- Assert.AreEqual("en-NZ", serializerProxy.Culture.ToString());
-
- serializerProxy.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
- Assert.AreEqual(DateFormatHandling.MicrosoftDateFormat, serializerProxy.DateFormatHandling);
-
- serializerProxy.DateFormatString = "yyyy";
- Assert.AreEqual("yyyy", serializerProxy.DateFormatString);
-
- serializerProxy.DateParseHandling = DateParseHandling.None;
- Assert.AreEqual(DateParseHandling.None, serializerProxy.DateParseHandling);
-
- serializerProxy.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- Assert.AreEqual(DateTimeZoneHandling.Utc, serializerProxy.DateTimeZoneHandling);
-
- serializerProxy.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
- Assert.AreEqual(DefaultValueHandling.IgnoreAndPopulate, serializerProxy.DefaultValueHandling);
-
- serializerProxy.FloatFormatHandling = FloatFormatHandling.Symbol;
- Assert.AreEqual(FloatFormatHandling.Symbol, serializerProxy.FloatFormatHandling);
-
- serializerProxy.FloatParseHandling = FloatParseHandling.Decimal;
- Assert.AreEqual(FloatParseHandling.Decimal, serializerProxy.FloatParseHandling);
-
- serializerProxy.Formatting = Formatting.Indented;
- Assert.AreEqual(Formatting.Indented, serializerProxy.Formatting);
-
- serializerProxy.MaxDepth = 9001;
- Assert.AreEqual(9001, serializerProxy.MaxDepth);
-
- serializerProxy.MissingMemberHandling = MissingMemberHandling.Error;
- Assert.AreEqual(MissingMemberHandling.Error, serializerProxy.MissingMemberHandling);
-
- serializerProxy.NullValueHandling = NullValueHandling.Ignore;
- Assert.AreEqual(NullValueHandling.Ignore, serializerProxy.NullValueHandling);
-
- serializerProxy.ObjectCreationHandling = ObjectCreationHandling.Replace;
- Assert.AreEqual(ObjectCreationHandling.Replace, serializerProxy.ObjectCreationHandling);
-
- serializerProxy.PreserveReferencesHandling = PreserveReferencesHandling.All;
- Assert.AreEqual(PreserveReferencesHandling.All, serializerProxy.PreserveReferencesHandling);
-
- serializerProxy.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- Assert.AreEqual(ReferenceLoopHandling.Ignore, serializerProxy.ReferenceLoopHandling);
-
- IdReferenceResolver referenceResolver = new IdReferenceResolver();
- serializerProxy.ReferenceResolver = referenceResolver;
- Assert.AreEqual(referenceResolver, serializerProxy.ReferenceResolver);
-
- serializerProxy.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii;
- Assert.AreEqual(StringEscapeHandling.EscapeNonAscii, serializerProxy.StringEscapeHandling);
-
- MemoryTraceWriter traceWriter = new MemoryTraceWriter();
- serializerProxy.TraceWriter = traceWriter;
- Assert.AreEqual(traceWriter, serializerProxy.TraceWriter);
-
- #if !(PORTABLE || PORTABLE40 || NETFX_CORE || NET20 || DNXCORE50)
- serializerProxy.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full;
- Assert.AreEqual(FormatterAssemblyStyle.Full, serializerProxy.TypeNameAssemblyFormat);
- #endif
-
- serializerProxy.TypeNameHandling = TypeNameHandling.All;
- Assert.AreEqual(TypeNameHandling.All, serializerProxy.TypeNameHandling);
- }
-
- #if !(NETFX_CORE || PORTABLE || PORTABLE40 || DNXCORE50)
- [Test]
- public void DeserializeISerializableIConvertible()
- {
- Ratio ratio = new Ratio(2, 1);
- string json = JsonConvert.SerializeObject(ratio);
-
- Assert.AreEqual(@"{""n"":2,""d"":1}", json);
-
- Ratio ratio2 = JsonConvert.DeserializeObject<Ratio>(json);
-
- Assert.AreEqual(ratio.Denominator, ratio2.Denominator);
- Assert.AreEqual(ratio.Numerator, ratio2.Numerator);
- }
-
- public class PreserveReferencesCallbackTestObject : ISerializable
- {
- internal string _stringValue;
- internal int _intValue;
- internal PersonReference _person1;
- internal PersonReference _person2;
- internal PersonReference _person3;
- internal PreserveReferencesCallbackTestObject _parent;
- internal SerializationInfo _serializationInfo;
-
- public PreserveReferencesCallbackTestObject(string stringValue, int intValue, PersonReference p1, PersonReference p2, PersonReference p3)
- {
- _stringValue = stringValue;
- _intValue = intValue;
- _person1 = p1;
- _person2 = p2;
- _person3 = p3;
- }
-
- protected PreserveReferencesCallbackTestObject(SerializationInfo info, StreamingContext context)
- {
- _serializationInfo = info;
- }
-
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- info.AddValue("stringValue", _stringValue);
- info.AddValue("intValue", _intValue);
- info.AddValue("person1", _person1, typeof(PersonReference));
- info.AddValue("person2", _person2, typeof(PersonReference));
- info.AddValue("person3", _person3, typeof(PersonReference));
- info.AddValue("parent", _parent, typeof(PreserveReferencesCallbackTestObject));
- }
-
- [OnDeserialized]
- private void OnDeserializedMethod(StreamingContext context)
- {
- if (_serializationInfo == null)
- return;
-
- _stringValue = _serializationInfo.GetString("stringValue");
- _intValue = _serializationInfo.GetInt32("intValue");
- _person1 = (PersonReference)_serializationInfo.GetValue("person1", typeof(PersonReference));
- _person2 = (PersonReference)_serializationInfo.GetValue("person2", typeof(PersonReference));
- _person3 = (PersonReference)_serializationInfo.GetValue("person3", typeof(PersonReference));
- _parent = (PreserveReferencesCallbackTestObject)_serializationInfo.GetValue("parent", typeof(PreserveReferencesCallbackTestObject));
-
- _serializationInfo = null;
- }
- }
-
- [Test]
- public void PreserveReferencesCallbackTest()
- {
- var p1 = new PersonReference
- {
- Name = "John Smith"
- };
- var p2 = new PersonReference
- {
- Name = "Mary Sue",
- };
-
- p1.Spouse = p2;
- p2.Spouse = p1;
-
- var obj = new PreserveReferencesCallbackTestObject("string!", 42, p1, p2, p1);
- obj._parent = obj;
-
- var settings = new JsonSerializerSettings
- {
- PreserveReferencesHandling = PreserveReferencesHandling.All,
- Formatting = Formatting.Indented
- };
-
- string json = JsonConvert.SerializeObject(obj, settings);
-
- StringAssert.AreEqual(json, @"{
- ""$id"": ""1"",
- ""stringValue"": ""string!"",
- ""intValue"": 42,
- ""person1"": {
- ""$id"": ""2"",
- ""Name"": ""John Smith"",
- ""Spouse"": {
- ""$id"": ""3"",
- ""Name"": ""Mary Sue"",
- ""Spouse"": {
- ""$ref"": ""2""
- }
- }
- },
- ""person2"": {
- ""$ref"": ""3""
- },
- ""person3"": {
- ""$ref"": ""2""
- },
- ""parent"": {
- ""$ref"": ""1""
- }
- }");
-
- PreserveReferencesCallbackTestObject obj2 = JsonConvert.DeserializeObject<PreserveReferencesCallbackTestObject>(json);
-
- Assert.AreEqual(obj._stringValue, obj2._stringValue);
- Assert.AreEqual(obj._intValue, obj2._intValue);
- Assert.AreEqual(obj._person1.Name, obj2._person1.Name);
- Assert.AreEqual(obj._person2.Name, obj2._person2.Name);
- Assert.AreEqual(obj._person3.Name, obj2._person3.Name);
- Assert.AreEqual(obj2._person1, obj2._person3);
- Assert.AreEqual(obj2._person1.Spouse, obj2._person2);
- Assert.AreEqual(obj2._person2.Spouse, obj2._person1);
- Assert.AreEqual(obj2._parent, obj2);
- }
- #endif
-
- [Test]
- public void DeserializeLargeFloat()
- {
- object o = JsonConvert.DeserializeObject("100000000000000000000000000000000000000.0");
-
- CustomAssert.IsInstanceOfType(typeof(double), o);
-
- Assert.IsTrue(MathUtils.ApproxEquals(1E+38, (double)o));
- }
-
- [Test]
- public void SerializeDeserializeRegex()
- {
- Regex regex = new Regex("(hi)", RegexOptions.CultureInvariant);
-
- string json = JsonConvert.SerializeObject(regex, Formatting.Indented);
-
- Regex r2 = JsonConvert.DeserializeObject<Regex>(json);
-
- Assert.AreEqual("(hi)", r2.ToString());
- Assert.AreEqual(RegexOptions.CultureInvariant, r2.Options);
- }
-
- [Test]
- public void EmbedJValueStringInNewJObject()
- {
- string s = null;
- var v = new JValue(s);
- var o = JObject.FromObject(new { title = v });
-
- JObject oo = new JObject
- {
- { "title", v }
- };
-
- string output = o.ToString();
-
- Assert.AreEqual(null, v.Value);
- Assert.AreEqual(JTokenType.String, v.Type);
-
- StringAssert.AreEqual(@"{
- ""title"": null
- }", output);
- }
-
- // bug: the generic member (T) that hides the base member will not
- // be used when serializing and deserializing the object,
- // resulting in unexpected behavior during serialization and deserialization.
-
- public class Foo1
- {
- public object foo { get; set; }
- }
-
- public class Bar1
- {
- public object bar { get; set; }
- }
-
- public class Foo1<T> : Foo1
- {
- public new T foo { get; set; }
-
- public T foo2 { get; set; }
- }
-
- public class FooBar1 : Foo1
- {
- public new Bar1 foo { get; set; }
- }
-
- [Test]
- public void BaseClassSerializesAsExpected()
- {
- var original = new Foo1 { foo = "value" };
- var json = JsonConvert.SerializeObject(original);
- var expectedJson = @"{""foo"":""value""}";
- Assert.AreEqual(expectedJson, json); // passes
- }
-
- [Test]
- public void BaseClassDeserializesAsExpected()
- {
- var json = @"{""foo"":""value""}";
- var deserialized = JsonConvert.DeserializeObject<Foo1>(json);
- Assert.AreEqual("value", deserialized.foo); // passes
- }
-
- [Test]
- public void DerivedClassHidingBasePropertySerializesAsExpected()
- {
- var original = new FooBar1 { foo = new Bar1 { bar = "value" } };
- var json = JsonConvert.SerializeObject(original);
- var expectedJson = @"{""foo"":{""bar"":""value""}}";
- Assert.AreEqual(expectedJson, json); // passes
- }
-
- [Test]
- public void DerivedClassHidingBasePropertyDeserializesAsExpected()
- {
- var json = @"{""foo"":{""bar"":""value""}}";
- var deserialized = JsonConvert.DeserializeObject<FooBar1>(json);
- Assert.IsNotNull(deserialized.foo); // passes
- Assert.AreEqual("value", deserialized.foo.bar); // passes
- }
-
- [Test]
- public void DerivedGenericClassHidingBasePropertySerializesAsExpected()
- {
- var original = new Foo1<Bar1> { foo = new Bar1 { bar = "value" }, foo2 = new Bar1 { bar = "value2" } };
- var json = JsonConvert.SerializeObject(original);
- var expectedJson = @"{""foo"":{""bar"":""value""},""foo2"":{""bar"":""value2""}}";
- Assert.AreEqual(expectedJson, json);
- }
-
- [Test]
- public void DerivedGenericClassHidingBasePropertyDeserializesAsExpected()
- {
- var json = @"{""foo"":{""bar"":""value""},""foo2"":{""bar"":""value2""}}";
- var deserialized = JsonConvert.DeserializeObject<Foo1<Bar1>>(json);
- Assert.IsNotNull(deserialized.foo2); // passes (bug only occurs for generics that /hide/ another property)
- Assert.AreEqual("value2", deserialized.foo2.bar); // also passes, with no issue
- Assert.IsNotNull(deserialized.foo);
- Assert.AreEqual("value", deserialized.foo.bar);
- }
-
- #if !(NETFX_CORE || DNXCORE50)
- [Test]
- public void ConversionOperator()
- {
- // Creating a simple dictionary that has a non-string key
- var dictStore = new Dictionary<DictionaryKeyCast, int>();
- for (var i = 0; i < 800; i++)
- {
- dictStore.Add(new DictionaryKeyCast(i.ToString(CultureInfo.InvariantCulture), i), i);
- }
- var settings = new JsonSerializerSettings { Formatting = Formatting.Indented };
- var jsonSerializer = JsonSerializer.Create(settings);
- …
Large files files are truncated, but you can click here to view the full file