-Fixed TypeNameHandling.Auto with some JsonConverters

-Fixed TypeNameHandling.Auto with JsonSerializer.Serialize inside a JsonConverter
-Changed assembly version to 6.0.0.0
-Marked async methods on JsonConverter as obsolete
This commit is contained in:
James Newton-King
2014-01-29 00:47:01 +13:00
parent c4da9cfb17
commit 4793c7b5da
10 changed files with 87 additions and 15 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
properties { properties {
$zipFileName = "Json60r1.zip" $zipFileName = "Json60r1.zip"
$majorVersion = "4.5" $majorVersion = "6.0"
$majorWithReleaseVersion = "6.0.1" $majorWithReleaseVersion = "6.0.1"
$version = GetVersion $majorWithReleaseVersion $version = GetVersion $majorWithReleaseVersion
$signAssemblies = $false $signAssemblies = $false
@@ -74,5 +74,5 @@ using System.Security;
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.1.16919")] [assembly: AssemblyFileVersion("6.0.1.16929")]
@@ -8775,7 +8775,7 @@ Parameter name: value",
ExtensionDataDeserializeWithNonDefaultConstructor c = new ExtensionDataDeserializeWithNonDefaultConstructor("Name!"); ExtensionDataDeserializeWithNonDefaultConstructor c = new ExtensionDataDeserializeWithNonDefaultConstructor("Name!");
c._extensionData = new Dictionary<string, JToken> c._extensionData = new Dictionary<string, JToken>
{ {
{"Key!", "Value!"} { "Key!", "Value!" }
}; };
string json = JsonConvert.SerializeObject(c, Formatting.Indented); string json = JsonConvert.SerializeObject(c, Formatting.Indented);
@@ -54,6 +54,61 @@ namespace Newtonsoft.Json.Tests.Serialization
[TestFixture] [TestFixture]
public class TypeNameHandlingTests : TestFixtureBase 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] [Test]
public void NestedValueObjects() public void NestedValueObjects()
{ {
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Tests.Serialization
#else #else
[JsonIgnore] [JsonIgnore]
#endif #endif
public string nonSerializedField; public string nonSerializedField;
public bool Equals(SerializableType other) public bool Equals(SerializableType other)
{ {
@@ -48,6 +48,10 @@ namespace Newtonsoft.Json.Converters
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{ {
Type t = value.GetType(); Type t = value.GetType();
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
PropertyInfo keyProperty = t.GetProperty(KeyName); PropertyInfo keyProperty = t.GetProperty(KeyName);
PropertyInfo valueProperty = t.GetProperty(ValueName); PropertyInfo valueProperty = t.GetProperty(ValueName);
@@ -56,9 +60,9 @@ namespace Newtonsoft.Json.Converters
writer.WriteStartObject(); writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName); 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); 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(); writer.WriteEndObject();
} }
+7
View File
@@ -642,6 +642,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<string> SerializeObjectAsync(object value)
{ {
return SerializeObjectAsync(value, Formatting.None, null); return SerializeObjectAsync(value, Formatting.None, null);
@@ -656,6 +657,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
{ {
return SerializeObjectAsync(value, formatting, null); return SerializeObjectAsync(value, formatting, null);
@@ -672,6 +674,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
{ {
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings)); return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
@@ -841,6 +844,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<T> DeserializeObjectAsync<T>(string value)
{ {
return DeserializeObjectAsync<T>(value, null); return DeserializeObjectAsync<T>(value, null);
@@ -859,6 +863,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
{ {
return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings)); return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
@@ -872,6 +877,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<object> DeserializeObjectAsync(string value)
{ {
return DeserializeObjectAsync(value, null, null); return DeserializeObjectAsync(value, null, null);
@@ -890,6 +896,7 @@ namespace Newtonsoft.Json
/// <returns> /// <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. /// 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> /// </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) public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
{ {
return Task.Factory.StartNew(() => DeserializeObject(value, type, settings)); return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
@@ -90,6 +90,6 @@ using System.Security;
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.1.16919")] [assembly: AssemblyFileVersion("6.0.1.16929")]
[assembly: CLSCompliant(true)] [assembly: CLSCompliant(true)]
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Serialization
/// Gets or sets the default members search flags. /// Gets or sets the default members search flags.
/// </summary> /// </summary>
/// <value>The default members search flags.</value> /// <value>The default members search flags.</value>
[ObsoleteAttribute("DefaultMembersSearchFlags is obsolete. Inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")] [ObsoleteAttribute("DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")]
public BindingFlags DefaultMembersSearchFlags { get; set; } public BindingFlags DefaultMembersSearchFlags { get; set; }
#else #else
private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public; private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public;
@@ -49,6 +49,7 @@ namespace Newtonsoft.Json.Serialization
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{ {
private JsonContract _rootContract; private JsonContract _rootContract;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>(); private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer; private JsonSerializerProxy _internalSerializer;
@@ -62,14 +63,13 @@ namespace Newtonsoft.Json.Serialization
if (jsonWriter == null) if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter"); throw new ArgumentNullException("jsonWriter");
if (objectType != null) _rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
_rootContract = Serializer._contractResolver.ResolveContract(objectType); _rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value); JsonContract contract = GetContractSafe(value);
try try
{ {
SerializeValue(jsonWriter, value, contract, null, null, null); SerializeValue(jsonWriter, value, contract, null, null, null);
} }
catch (Exception ex) catch (Exception ex)
@@ -87,6 +87,12 @@ namespace Newtonsoft.Json.Serialization
throw; 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() private JsonSerializerProxy GetInternalSerializer()
@@ -869,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) if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true; return true;
} }
else if (_rootContract != null && _serializeStack.Count == 1) else if (_rootContract != null && _serializeStack.Count == _rootLevel)
{ {
if (contract.UnderlyingType != _rootContract.CreatedType) if (contract.UnderlyingType != _rootContract.CreatedType)
return true; return true;