We have been using .NET Core 3.1 to serialize/deserialize with this code:
public UserData Clone()
{
return ((ICloneable)this).Clone() as UserData;
}
object ICloneable.Clone()
{
BinaryFormatter binary = new BinaryFormatter();
using (var ms = new MemoryStream())
{
binary.Serialize(ms, this);
ms.Flush();
ms.Position = 0;
return binary.Deserialize(ms);
}
}
var filteredData = records.Clone();
But with the upgrade to .NET 6, the following code throws an error:
BinaryFormatter serialization & deserialization are disabled within the application
I tried to update the code as below using JsonSerializer as below:
JsonSerializer serializer = new JsonSerializer();
using (var ms = new MemoryStream())
{
var jsonTextWriter = new JsonTextWriter(new StreamWriter(ms));
Serialize the object to JSON and write it to the MemoryStream.
serializer.Serialize(jsonTextWriter, this);
ms.Flush();
ms.Position = 0;
var jsonTextReader = new JsonTextReader(new StreamReader(ms));
return serializer.Deserialize<object>(jsonTextReader);
}
Above code builds fine, but when called, filteredData
returns null:
var filteredData = records.Clone();
I am not sure if I am using this in a correct way or something is missing. Could anyone provide their inputs? Thanks
//Updated with new code
object ICloneable.Clone()
{
var serialized = JsonConvert.SerializeObject(this);
return JsonConvert.DeserializeObject<UserData>(serialized);
}