Search code examples
c#.netjson.netjsonconvert

C# cloning an object that has some get properties only


My object has some get properties (no setter) lets call them xyz for conversation sake I am trying to clone the object with jsonconvert.deserialise(serialise(object)) but xyz does not have same value as the source

Any suggestions on how the object can be copied same as source

Minimal code

public class MyClass
{
    public Guid Id { get; }

    public MyClass()
    {
        Id = Guid.NewGuid();
    }
}

In main class:

MyClass myclassobj = new MyClass();
MyClass duplicateobj = JsonSerializer.Deserialize<MyClass>(JsonSerializer.Serialize(myclassobj));

Console.WriteLine("source object " + myclassobj.Id);
Console.WriteLine("target object " + duplicateobj.Id);

Output:

source object 9b1e2bc8-be7a-44f9-ba6a-347cf58cb42e
target object 9f2e08a2-11b8-4aa5-9999-c24765ce2a80 <- this should be same as above

Solution

  • You are seeing such behavior as converter uses parameterless constructor to initialize object. So the property is set to Guid.NewGuid() there and thus, having different value.

    And it is presisted, as it is readonly. So converter basically cannot set different value for it.

    So in result, you see different ID in deserialized class.

    You can try options mentioned here: Deserialize read-only variables. Based on that you should define constructor with attribute:

    [JsonConstructor]
    public MyClass(Guid id)
    {
        Id = id;
    }
    

    Then the output is:

    source object 2e4f73a6-57a5-44d3-bb53-29a574578cbd
    target object 2e4f73a6-57a5-44d3-bb53-29a574578cbd