-Added generic JsonConvert.SerializeObject methods
-Fixed JToken.ToObject not using StringEnumConverter on enums
This commit is contained in:
@@ -133,7 +133,7 @@ namespace Newtonsoft.Json.Tests.Converters
|
|||||||
[Test]
|
[Test]
|
||||||
public void SerializeNullRoot()
|
public void SerializeNullRoot()
|
||||||
{
|
{
|
||||||
string json = JsonConvert.SerializeObject(null, typeof(DataSet), new JsonSerializerSettings
|
string json = JsonConvert.SerializeObject<DataSet>(null, new JsonSerializerSettings
|
||||||
{
|
{
|
||||||
Formatting = Formatting.Indented
|
Formatting = Formatting.Indented
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -481,7 +481,7 @@ namespace Newtonsoft.Json.Tests.Converters
|
|||||||
[Test]
|
[Test]
|
||||||
public void SerializeNullRoot()
|
public void SerializeNullRoot()
|
||||||
{
|
{
|
||||||
string json = JsonConvert.SerializeObject(null, typeof(DataTable), new JsonSerializerSettings
|
string json = JsonConvert.SerializeObject<DataTable>(null, new JsonSerializerSettings
|
||||||
{
|
{
|
||||||
Formatting = Formatting.Indented
|
Formatting = Formatting.Indented
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -45,6 +45,9 @@ using NUnit.Framework;
|
|||||||
#endif
|
#endif
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Threading;
|
||||||
#if NET20
|
#if NET20
|
||||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||||
#else
|
#else
|
||||||
@@ -3452,6 +3455,73 @@ null//comment
|
|||||||
Assert.IsFalse(r.Read());
|
Assert.IsFalse(r.Read());
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if !DNXCORE50
|
||||||
|
[Test]
|
||||||
|
[Ignore]
|
||||||
|
public void ReadFromNetworkStream()
|
||||||
|
{
|
||||||
|
const int port = 11999;
|
||||||
|
const int jsonArrayElementsCount = 193;
|
||||||
|
|
||||||
|
var serverStartedEvent = new ManualResetEvent(false);
|
||||||
|
var clientReceivedEvent = new ManualResetEvent(false);
|
||||||
|
|
||||||
|
#region server
|
||||||
|
ThreadPool.QueueUserWorkItem(work =>
|
||||||
|
{
|
||||||
|
var server = new TcpListener(IPAddress.Parse("0.0.0.0"), port);
|
||||||
|
server.Start();
|
||||||
|
|
||||||
|
serverStartedEvent.Set();
|
||||||
|
|
||||||
|
var serverSocket = server.AcceptSocket();
|
||||||
|
|
||||||
|
var jsonString = "[\r\n" + String.Join(",", Enumerable.Repeat(" \"testdata\"\r\n", jsonArrayElementsCount).ToArray()) + "]";
|
||||||
|
var bytes = new UTF8Encoding().GetBytes(jsonString);
|
||||||
|
serverSocket.Send(bytes);
|
||||||
|
Console.WriteLine("server send: " + bytes.Length);
|
||||||
|
|
||||||
|
|
||||||
|
clientReceivedEvent.WaitOne();
|
||||||
|
|
||||||
|
});
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
serverStartedEvent.WaitOne();
|
||||||
|
|
||||||
|
|
||||||
|
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||||
|
socket.Blocking = false;
|
||||||
|
socket.Connect("127.0.0.1", port);
|
||||||
|
|
||||||
|
var stream = new NetworkStream(socket);
|
||||||
|
var serializer = new JsonSerializer();
|
||||||
|
|
||||||
|
int i = 0;
|
||||||
|
using (var sr = new StreamReader(stream, new UTF8Encoding(), false))
|
||||||
|
using (var jsonTextReader = new JsonTextReader(sr))
|
||||||
|
{
|
||||||
|
while (jsonTextReader.Read())
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
|
||||||
|
if (i == 193)
|
||||||
|
{
|
||||||
|
string s = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"{i} - {jsonTextReader.TokenType} - {jsonTextReader.Value}");
|
||||||
|
}
|
||||||
|
//var result = serializer.Deserialize(jsonTextReader).ToString();
|
||||||
|
//Console.WriteLine("client receive: " + new UTF8Encoding().GetBytes(result).Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
clientReceivedEvent.Set();
|
||||||
|
|
||||||
|
Console.WriteLine("Done");
|
||||||
|
}
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ToggleReaderError : TextReader
|
public class ToggleReaderError : TextReader
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ using Newtonsoft.Json.Utilities.LinqBridge;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
#endif
|
#endif
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
namespace Newtonsoft.Json.Tests.Linq
|
namespace Newtonsoft.Json.Tests.Linq
|
||||||
{
|
{
|
||||||
@@ -1329,6 +1330,57 @@ keyword such as type of business.""
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if !(NET20)
|
||||||
|
[JsonConverter(typeof(StringEnumConverter))]
|
||||||
|
public enum FooBar
|
||||||
|
{
|
||||||
|
[EnumMember(Value = "SOME_VALUE")]
|
||||||
|
SomeValue,
|
||||||
|
|
||||||
|
[EnumMember(Value = "SOME_OTHER_VALUE")]
|
||||||
|
SomeOtherValue
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MyObject
|
||||||
|
{
|
||||||
|
public FooBar FooBar { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void ToObject_Enum_Converter()
|
||||||
|
{
|
||||||
|
JObject o = JObject.Parse("{'FooBar':'SOME_OTHER_VALUE'}");
|
||||||
|
|
||||||
|
FooBar e = o["FooBar"].ToObject<FooBar>();
|
||||||
|
Assert.AreEqual(FooBar.SomeOtherValue, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum FooBarNoEnum
|
||||||
|
{
|
||||||
|
[EnumMember(Value = "SOME_VALUE")]
|
||||||
|
SomeValue,
|
||||||
|
|
||||||
|
[EnumMember(Value = "SOME_OTHER_VALUE")]
|
||||||
|
SomeOtherValue
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MyObjectNoEnum
|
||||||
|
{
|
||||||
|
public FooBarNoEnum FooBarNoEnum { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void ToObject_Enum_NoConverter()
|
||||||
|
{
|
||||||
|
JObject o = JObject.Parse("{'FooBarNoEnum':'SOME_OTHER_VALUE'}");
|
||||||
|
|
||||||
|
ExceptionAssert.Throws<ArgumentException>(() =>
|
||||||
|
{
|
||||||
|
o["FooBarNoEnum"].ToObject<FooBarNoEnum>();
|
||||||
|
}, "Could not convert 'SOME_OTHER_VALUE' to FooBarNoEnum.");
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public void SerializeWithNoRedundentIdPropertiesTest()
|
public void SerializeWithNoRedundentIdPropertiesTest()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -245,6 +245,34 @@ namespace Newtonsoft.Json.Tests.Serialization
|
|||||||
}", json);
|
}", json);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void SerializeRootTypeNameAutoWithJsonConvert_Generic()
|
||||||
|
{
|
||||||
|
string json = JsonConvert.SerializeObject<object>(new WagePerson(), Formatting.Indented, new JsonSerializerSettings
|
||||||
|
{
|
||||||
|
TypeNameHandling = TypeNameHandling.Auto
|
||||||
|
});
|
||||||
|
|
||||||
|
StringAssert.AreEqual(@"{
|
||||||
|
""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
|
||||||
|
""HourlyWage"": 0.0,
|
||||||
|
""Name"": null,
|
||||||
|
""BirthDate"": ""0001-01-01T00:00:00"",
|
||||||
|
""LastModified"": ""0001-01-01T00:00:00""
|
||||||
|
}", json);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void SerializeRootTypeNameAutoWithJsonConvert_Generic2()
|
||||||
|
{
|
||||||
|
string json = JsonConvert.SerializeObject<object>(new WagePerson(), new JsonSerializerSettings
|
||||||
|
{
|
||||||
|
TypeNameHandling = TypeNameHandling.Auto
|
||||||
|
});
|
||||||
|
|
||||||
|
StringAssert.AreEqual(@"{""$type"":""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",""HourlyWage"":0.0,""Name"":null,""BirthDate"":""0001-01-01T00:00:00"",""LastModified"":""0001-01-01T00:00:00""}", json);
|
||||||
|
}
|
||||||
|
|
||||||
public class Wrapper
|
public class Wrapper
|
||||||
{
|
{
|
||||||
public IList<EmployeeReference> Array { get; set; }
|
public IList<EmployeeReference> Array { get; set; }
|
||||||
|
|||||||
@@ -530,6 +530,17 @@ namespace Newtonsoft.Json
|
|||||||
return SerializeObject(value, null, (JsonSerializerSettings)null);
|
return SerializeObject(value, null, (JsonSerializerSettings)null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Serializes the specified object to a JSON string.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">The type of the object to serialize.</typeparam>
|
||||||
|
/// <param name="value">The object to serialize.</param>
|
||||||
|
/// <returns>A JSON string representation of the object.</returns>
|
||||||
|
public static string SerializeObject<T>(object value)
|
||||||
|
{
|
||||||
|
return SerializeObject(value, typeof(T), (JsonSerializerSettings)null);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serializes the specified object to a JSON string using formatting.
|
/// Serializes the specified object to a JSON string using formatting.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -543,6 +554,20 @@ namespace Newtonsoft.Json
|
|||||||
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
|
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Serializes the specified object to a JSON string using formatting.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">The type of the object to serialize.</typeparam>
|
||||||
|
/// <param name="value">The object to serialize.</param>
|
||||||
|
/// <param name="formatting">Indicates how the output is formatted.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A JSON string representation of the object.
|
||||||
|
/// </returns>
|
||||||
|
public static string SerializeObject<T>(object value, Formatting formatting)
|
||||||
|
{
|
||||||
|
return SerializeObject(value, typeof(T), (JsonSerializerSettings)null);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
|
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -588,6 +613,21 @@ namespace Newtonsoft.Json
|
|||||||
return SerializeObject(value, null, settings);
|
return SerializeObject(value, null, settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">The type of the object to serialize.</typeparam>
|
||||||
|
/// <param name="value">The object to serialize.</param>
|
||||||
|
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
|
||||||
|
/// If this is null, default serialization settings will be used.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A JSON string representation of the object.
|
||||||
|
/// </returns>
|
||||||
|
public static string SerializeObject<T>(T value, JsonSerializerSettings settings)
|
||||||
|
{
|
||||||
|
return SerializeObject(value, typeof(T), settings);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
|
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -624,6 +664,22 @@ namespace Newtonsoft.Json
|
|||||||
return SerializeObject(value, null, formatting, settings);
|
return SerializeObject(value, null, formatting, settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">The type of the object to serialize.</typeparam>
|
||||||
|
/// <param name="value">The object to serialize.</param>
|
||||||
|
/// <param name="formatting">Indicates how the output is formatted.</param>
|
||||||
|
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
|
||||||
|
/// If this is null, default serialization settings will be used.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A JSON string representation of the object.
|
||||||
|
/// </returns>
|
||||||
|
public static string SerializeObject<T>(T value, Formatting formatting, JsonSerializerSettings settings)
|
||||||
|
{
|
||||||
|
return SerializeObject(value, typeof(T), formatting, settings);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
|
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -934,6 +990,7 @@ namespace Newtonsoft.Json
|
|||||||
#endif
|
#endif
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
#region Populate
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Populates the object with values from the JSON string.
|
/// Populates the object with values from the JSON string.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -987,7 +1044,9 @@ namespace Newtonsoft.Json
|
|||||||
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
|
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Xml
|
||||||
#if !(PORTABLE40 || PORTABLE || DOTNET)
|
#if !(PORTABLE40 || PORTABLE || DOTNET)
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serializes the XML node to a JSON string.
|
/// Serializes the XML node to a JSON string.
|
||||||
@@ -1145,5 +1204,6 @@ namespace Newtonsoft.Json
|
|||||||
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
|
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1948,13 +1948,14 @@ namespace Newtonsoft.Json.Linq
|
|||||||
{
|
{
|
||||||
if (Type == JTokenType.String)
|
if (Type == JTokenType.String)
|
||||||
{
|
{
|
||||||
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return Enum.Parse(enumType, (string)this, true);
|
// use serializer so JsonConverter(typeof(StringEnumConverter)) + EnumMemberAttributes are respected
|
||||||
|
return ToObject(objectType, JsonSerializer.CreateDefault());
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
|
||||||
throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex);
|
throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ namespace Newtonsoft.Json.Serialization
|
|||||||
{
|
{
|
||||||
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
|
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
|
||||||
{
|
{
|
||||||
private JsonContract _rootContract;
|
private Type _rootType;
|
||||||
private int _rootLevel;
|
private int _rootLevel;
|
||||||
private readonly List<object> _serializeStack = new List<object>();
|
private readonly List<object> _serializeStack = new List<object>();
|
||||||
|
|
||||||
@@ -64,7 +64,7 @@ namespace Newtonsoft.Json.Serialization
|
|||||||
throw new ArgumentNullException("jsonWriter");
|
throw new ArgumentNullException("jsonWriter");
|
||||||
}
|
}
|
||||||
|
|
||||||
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
|
_rootType = objectType;
|
||||||
_rootLevel = _serializeStack.Count + 1;
|
_rootLevel = _serializeStack.Count + 1;
|
||||||
|
|
||||||
JsonContract contract = GetContractSafe(value);
|
JsonContract contract = GetContractSafe(value);
|
||||||
@@ -99,7 +99,7 @@ namespace Newtonsoft.Json.Serialization
|
|||||||
{
|
{
|
||||||
// clear root contract to ensure that if level was > 1 then it won't
|
// clear root contract to ensure that if level was > 1 then it won't
|
||||||
// accidently be used for non root values
|
// accidently be used for non root values
|
||||||
_rootContract = null;
|
_rootType = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1014,9 +1014,11 @@ namespace Newtonsoft.Json.Serialization
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
|
else if (_rootType != null && _serializeStack.Count == _rootLevel)
|
||||||
{
|
{
|
||||||
if (contract.UnderlyingType != _rootContract.CreatedType)
|
JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType);
|
||||||
|
|
||||||
|
if (contract.UnderlyingType != rootContract.CreatedType)
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user