I have a Dictionary<string,object>
where I save objects to parse to my plugin system, some of these objects need to be a copy not the original so I use this DeepClone method:
public static T DeepCloneJSON<T>(this T Obj)
{
var text = JsonSerializer.Serialize(Obj);
return JsonSerializer.Deserialize<T>(text);
}
for example, if I do :
var dict = new Dictionary<string,object>(){
{"someKey",new List<MyClass>(){new MyClass()}}
}
var copy = dict["someKey"].DeepCloneJSON();
var cast = (List<MyClass>)copy;
i get a System.InvalidCastException, but if i use a MemoryStream DeepCopy method i don't get this exception, like this one:
public static T DeepCloneMemoryStream<T>(this T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
so, I would like to know why I get this exception using a System.text.json based DeepClone Method and if it is possible to do this with a System.text.json because in my tests it presents to be faster and use less memory than a MemoryStream based onde.