-Added support for Serializable attribute and MemberSerialization.Fields

-Added support for ignoring properties with NonSerializable attribute
-Added MaxDepth to JsonReader/JsonSerializer/JsonSerializerSettings
This commit is contained in:
James Newton-King
2012-04-08 19:33:09 +12:00
parent 83618b1ea0
commit e3cec969ef
20 changed files with 620 additions and 118 deletions
@@ -44,6 +44,25 @@ namespace Newtonsoft.Json.Tests
[TestFixture]
public class JsonTextReaderTest : TestFixtureBase
{
[Test]
public void SurrogatePairValid()
{
string json = @"{ ""MATHEMATICAL ITALIC CAPITAL ALPHA"": ""\uD835\uDEE2"" }";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
string s = reader.Value.ToString();
StringInfo stringInfo = new StringInfo(s);
Assert.AreEqual(1, stringInfo.LengthInTextElements);
}
[Test]
public void CloseInput()
{
@@ -2195,6 +2214,26 @@ bye", reader.Value);
reader.Read();
}
[Test]
public void MaxDepth()
{
string json = "[[]]";
JsonTextReader reader = new JsonTextReader(new StringReader(json))
{
MaxDepth = 1
};
Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>(
"This reader's MaxDepth of 1 has been exceeded.",
() =>
{
Assert.IsTrue(reader.Read());
});
}
[Test]
public void ReadingFromSlowStream()
{
@@ -94,6 +94,7 @@
<Compile Include="Linq\JRawTests.cs" />
<Compile Include="Serialization\ConstructorHandlingTests.cs" />
<Compile Include="Serialization\JsonPropertyCollectionTests.cs" />
<Compile Include="Serialization\WebApiIntegrationTests.cs" />
<Compile Include="TestObjects\Bar.cs" />
<Compile Include="TestObjects\Car.cs" />
<Compile Include="TestObjects\Computer.cs" />
@@ -139,6 +139,7 @@
<Compile Include="Serialization\DefaultValueHandlingTests.cs" />
<Compile Include="Serialization\DynamicTests.cs" />
<Compile Include="Serialization\NullValueHandlingTests.cs" />
<Compile Include="Serialization\WebApiIntegrationTests.cs" />
<Compile Include="TestObjects\Bar.cs" />
<Compile Include="TestObjects\Car.cs" />
<Compile Include="TestObjects\Computer.cs" />
@@ -139,6 +139,7 @@
<Compile Include="Serialization\SerializationErrorHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
<Compile Include="Serialization\WebApiIntegrationTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
@@ -102,6 +102,7 @@
<Compile Include="Serialization\SerializationErrorHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
<Compile Include="Serialization\WebApiIntegrationTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
@@ -144,6 +144,7 @@
<Compile Include="Serialization\ContractResolverTests.cs" />
<Compile Include="Serialization\DefaultValueHandlingTests.cs" />
<Compile Include="Serialization\DynamicTests.cs" />
<Compile Include="Serialization\WebApiIntegrationTests.cs" />
<Compile Include="Serialization\JsonPropertyCollectionTests.cs" />
<Compile Include="Serialization\NullValueHandlingTests.cs" />
<Compile Include="TestObjects\Bar.cs" />
@@ -72,5 +72,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.1.14719")]
[assembly: AssemblyFileVersion("4.5.1.14808")]
#endif
@@ -256,27 +256,6 @@ namespace Newtonsoft.Json.Tests.Schema
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void Generate_NumberFormatInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(NumberFormatInfo));
string json = schema.ToString();
Console.WriteLine(json);
// Assert.AreEqual(@"{
// ""type"": ""object"",
// ""additionalProperties"": {
// ""type"": ""array"",
// ""items"": {
// ""type"": ""string""
// }
// }
//}", json);
}
[Test]
public void CircularReferenceError()
{
@@ -389,7 +368,12 @@ namespace Newtonsoft.Json.Tests.Schema
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CustomDirectoryInfoMapper();
generator.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);
@@ -468,7 +452,12 @@ namespace Newtonsoft.Json.Tests.Schema
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.ContractResolver = new CustomDirectoryInfoMapper();
serializer.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableInterface = true
#endif
};
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
@@ -483,9 +472,14 @@ namespace Newtonsoft.Json.Tests.Schema
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver();
generator.ContractResolver = new CamelCasePropertyNamesContractResolver()
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof (Version), true);
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
@@ -525,6 +519,68 @@ namespace Newtonsoft.Json.Tests.Schema
}", json);
}
#if !SILVERLIGHT
[Test]
public void GenerateSchemaSerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof (Version), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""_Major"": {
""required"": true,
""type"": ""integer""
},
""_Minor"": {
""required"": true,
""type"": ""integer""
},
""_Build"": {
""required"": true,
""type"": ""integer""
},
""_Revision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4));
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
Assert.AreEqual(@"{
""_Major"": 1,
""_Minor"": 2,
""_Build"": 3,
""_Revision"": 4
}", jsonWriter.Token.ToString());
Version version = jsonWriter.Token.ToObject<Version>();
Assert.AreEqual(1, version.Major);
Assert.AreEqual(2, version.Minor);
Assert.AreEqual(3, version.Build);
Assert.AreEqual(4, version.Revision);
}
#endif
public enum SortTypeFlag
{
No = 0,
@@ -77,6 +77,9 @@ using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
#if !(SILVERLIGHT || NETFX_CORE)
using System.Drawing;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
@@ -490,8 +493,6 @@ keyword such as type of business.""
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc),
};
string result;
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof (List<DateTime>));
@@ -501,7 +502,7 @@ keyword such as type of business.""
string expected = sr.ReadToEnd();
result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
string result = JsonConvert.SerializeObject(testDates, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
Assert.AreEqual(expected, result);
}
@@ -1582,8 +1583,10 @@ keyword such as type of business.""
}
}";
DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(json,
new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace});
DictionaryInterfaceClass c = JsonConvert.DeserializeObject<DictionaryInterfaceClass>(
json,
new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace});
Assert.AreEqual("Name!", c.Name);
Assert.AreEqual(1, c.Dictionary.Count);
Assert.AreEqual(11, c.Dictionary["Item"]);
@@ -2029,7 +2032,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
)]
public void SerializePropertyGetError()
{
JsonConvert.SerializeObject(new MemoryStream());
JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableAttribute = true
#endif
}
});
}
[Test]
@@ -2040,7 +2051,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
)]
public void DeserializePropertySetError()
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}");
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableAttribute = true
#endif
}
});
}
[Test]
@@ -2051,7 +2070,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
)]
public void DeserializeEnsureTypeEmptyStringToIntError()
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}");
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableAttribute = true
#endif
}
});
}
[Test]
@@ -2062,7 +2089,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
)]
public void DeserializeEnsureTypeNullToIntError()
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}");
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
#if !(SILVERLIGHT || NETFX_CORE)
IgnoreSerializableAttribute = true
#endif
}
});
}
[Test]
@@ -5785,6 +5820,119 @@ Parameter name: value"
Assert.AreEqual(person.Name, roundtrippedPerson.Name);
}
#endif
#if !(SILVERLIGHT || NETFX_CORE)
[Test]
public void MetroBlogPost()
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2012, 4, 1);
product.Price = 3.99M;
product.Sizes = new []{"Small", "Medium", "Large"};
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2012-04-01T00:00:00",
// "Price": 3.99,
// "Sizes": [ "Small", "Medium", "Large" ]
//}
string metroJson = JsonConvert.SerializeObject(product, new JsonSerializerSettings
{
ContractResolver = new MetroPropertyNameResolver(),
Converters = { new MetroStringConverter() },
Formatting = Formatting.Indented
});
Assert.AreEqual(metroJson, @"{
"":::NAME:::"": "":::APPLE:::"",
"":::EXPIRYDATE:::"": ""2012-04-01T00:00:00"",
"":::PRICE:::"": 3.99,
"":::SIZES:::"": [
"":::SMALL:::"",
"":::MEDIUM:::"",
"":::LARGE:::""
]
}");
//{
// ":::NAME:::": ":::APPLE:::",
// ":::EXPIRYDATE:::": "2012-04-01T00:00:00",
// ":::PRICE:::": 3.99,
// ":::SIZES:::": [ ":::SMALL:::", ":::MEDIUM:::", ":::LARGE:::" ]
//}
Color[] colors = new []{ Color.Blue, Color.Red, Color.Yellow, Color.Green, Color.Black, Color.Brown };
string json1 = JsonConvert.SerializeObject(colors);
//[":::GRAY:::", ":::GRAY:::", ":::GRAY:::", ":::GRAY:::", ":::BLACK:::", ":::GRAY:::"]
Assert.AreEqual(json1, @"[""Blue"",""Red"",""Yellow"",""Green"",""Black"",""Brown""]");
string json2 = JsonConvert.SerializeObject(colors, new JsonSerializerSettings
{
ContractResolver = new MetroPropertyNameResolver(),
Converters = { new MetroStringConverter(), new MetroColorConverter() },
Formatting = Formatting.Indented
});
Assert.AreEqual(json2, @"[
"":::GRAY:::"",
"":::GRAY:::"",
"":::GRAY:::"",
"":::GRAY:::"",
"":::BLACK:::"",
"":::GRAY:::""
]");
}
public class MetroStringConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(":::" + value.ToString().ToUpper() + ":::");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return existingValue;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (string);
}
}
public class MetroPropertyNameResolver : DefaultContractResolver
{
protected internal override string ResolvePropertyName(string propertyName)
{
return ":::" + propertyName.ToUpper() + ":::";
}
}
public class MetroColorConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Color color = (Color) value;
Color fixedColor = (color == Color.White || color == Color.Black) ? color : Color.Gray;
writer.WriteValue(":::" + fixedColor.ToKnownColor().ToString().ToUpper() + ":::");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return Enum.Parse(typeof (Color), reader.Value.ToString());
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (Color);
}
}
#endif
}
public class PersonWithPrivateConstructor
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.IO;
#if !NET20
using System.Linq;
#endif
using System.Text;
using NUnit.Framework;
#if !(SILVERLIGHT || NETFX_CORE || NET20)
using System.Runtime.Serialization.Json;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class WebApiIntegrationTests : TestFixtureBase
{
[Test]
public void SerializeSerializableType()
{
SerializableType serializableType = new SerializableType("protected")
{
publicField = "public",
protectedInternalField = "protected internal",
internalField = "internal",
PublicProperty = "private",
nonSerializedField = "Error"
};
#if !(SILVERLIGHT || NETFX_CORE || NET20)
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(SerializableType));
dataContractJsonSerializer.WriteObject(ms, serializableType);
string dtJson = Encoding.UTF8.GetString(ms.ToArray());
string dtExpected = @"{""internalField"":""internal"",""privateField"":""private"",""protectedField"":""protected"",""protectedInternalField"":""protected internal"",""publicField"":""public""}";
Assert.AreEqual(dtExpected, dtJson);
#endif
string expected = "{\"publicField\":\"public\",\"internalField\":\"internal\",\"protectedInternalField\":\"protected internal\",\"protectedField\":\"protected\",\"privateField\":\"private\"}";
string json = JsonConvert.SerializeObject(serializableType);
Assert.AreEqual(expected, json);
}
#if !SILVERLIGHT
[Test]
public void SerializeInheritedType()
{
InheritedType serializableType = new InheritedType("protected")
{
publicField = "public",
protectedInternalField = "protected internal",
internalField = "internal",
PublicProperty = "private",
nonSerializedField = "Error",
inheritedTypeField = "inherited"
};
string json = JsonConvert.SerializeObject(serializableType);
Assert.AreEqual(@"{""inheritedTypeField"":""inherited"",""publicField"":""public"",""PublicProperty"":""private""}", json);
}
#endif
}
public class InheritedType : SerializableType
{
public string inheritedTypeField;
public InheritedType(string protectedFieldValue) : base(protectedFieldValue)
{
}
}
#if !(SILVERLIGHT || NETFX_CORE)
[Serializable]
#else
[JsonObject(MemberSerialization.Fields)]
#endif
public class SerializableType : IEquatable<SerializableType>
{
public SerializableType(string protectedFieldValue)
{
this.protectedField = protectedFieldValue;
}
public string publicField;
internal string internalField;
protected internal string protectedInternalField;
protected string protectedField;
private string privateField;
public string PublicProperty
{
get
{
return privateField;
}
set
{
this.privateField = value;
}
}
#if !(SILVERLIGHT || NETFX_CORE)
[NonSerialized]
#else
[JsonIgnore]
#endif
public string nonSerializedField;
public bool Equals(SerializableType other)
{
return this.publicField == other.publicField &&
this.internalField == other.internalField &&
this.protectedInternalField == other.protectedInternalField &&
this.protectedField == other.protectedField &&
this.privateField == other.privateField;
}
}
}