1
public class DynamicDictionary : System.Dynamic.DynamicObject
{
    Dictionary<string, object> dictionary = new Dictionary<string, object>();
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        string name = binder.Name;
        return dictionary.TryGetValue(name, out result);
    }
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }
    public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames()
    {
        return this.dictionary?.Keys;
    }
}
public class SerializeExtensions
{
    public string Name { get; set; }
    public DynamicDictionary DynamicObj { get; set; }
}

Please consider the above like my class.

I have a List of SerializeExtensions collection. Now I have to deep clone this list of collections.

This has been properly cloned when I am using the below code.

JsonConvert.DeserializeObject<List<SerializeExtensions>>(JsonConvert.SerializeObject(collection));

This serialization belongs to Newtonsoft.Json. But I need to System.Text.Json for serialization.

So when I am using System.Text.Json serialization, the DynamicObject field has reset to empty. the below code has used.

JsonSerializer.Deserialize<List<SerializeExtensions>>(JsonSerializer.Serialize(collection));

After the serialization, I am getting the output like below

Name: "John"
DynamicObj: {}

Actually, the DynamicObj count is 4 in my case before serialization.

is there any possible to deep clone this kind of class?

dbc
  • 104,963
  • 20
  • 228
  • 340
Vengatesh
  • 49
  • 3
  • https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-of-an-object-in-net – MDT Aug 25 '21 at 05:30
  • you will need a converter, see this question https://stackoverflow.com/questions/60792311/system-text-json-and-dynamically-parsing-polymorphic-objects – Michael Gabbay Aug 25 '21 at 05:31
  • @MichaelGabbay For your information, I dont want use the Newtonsoft.Json – Vengatesh Aug 25 '21 at 05:56
  • @Manti_Core the BinaryFormatter.serialize is deprecated.. is there any alternative option for this – Vengatesh Aug 25 '21 at 05:58
  • 1
    @Vengatesh the link is System.Text.Json question and the answere – Michael Gabbay Aug 25 '21 at 06:01
  • `System.Text.Json` does not support dynamic objects in .NET 5. It is coming in .NET 6, see [Writable DOM and dynamic support for 6.0 #163](https://github.com/dotnet/designs/pull/163). In the meantime you will need to use a custom converter, such as [this one](https://stackoverflow.com/a/65974452/3744182) from [C# - Deserializing nested json to nested Dictionary](https://stackoverflow.com/q/65972825/3744182) which works for `ExpandoObject` and could be adapted to your `DynamicDictionary`. – dbc Aug 30 '21 at 21:15

0 Answers0