Created
October 27, 2016 10:18
-
-
Save LindaLawton/4f64f929ba8beb28edea95316257849f to your computer and use it in GitHub Desktop.
Perform a deep Copy of the object, using Json as a serialisation method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System; | |
using System.Globalization; | |
namespace HttpStuff.Util | |
{ | |
public static class Extensions | |
{ | |
/// <summary> | |
/// Perform a deep Copy of the object, using Json as a serialisation method. | |
/// </summary> | |
/// <typeparam name="T">The type of object being copied.</typeparam> | |
/// <param name="source">The object instance to copy.</param> | |
/// <returns>The copied object.</returns> | |
public static T CloneJson<T>(this T source) | |
{ | |
// Don't serialize a null object, simply return the default for that object | |
if (Object.ReferenceEquals(source, null)) | |
{ | |
return default(T); | |
} | |
// initialize inner objects individually | |
// for example in default constructor some list property initialized with some values, | |
// but in 'source' these items are cleaned - | |
// without ObjectCreationHandling.Replace default constructor values will be added to result | |
var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }; | |
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment