-1

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
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69

1 Answers1

0

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
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • But the jsondesrialiser overwrites the properties later, (after the constructor call). the main issue here is the not having a set;, i cant add set because of restrictions – rashid khan Jan 19 '22 at 07:14
  • 1
    After the cosntructor call - you know that readonly varibles can be only set IN THE CONSTRUCTOR, right? That's why it does not work - I mentioned that in the answer. Please read carefully. – Michał Turczyn Jan 19 '22 at 07:16
  • https://stackoverflow.com/users/7132550/micha%c5%82-turczyn Michal Turczyn I know it doesn't. What my question is about is that is there a way to somehow workaround this scenario. 1. property needs to be readonly 2. need to clone – rashid khan Jan 19 '22 at 10:32
  • @rashidkhan Add constructor accepting Guid as parameter – Michał Turczyn Jan 19 '22 at 11:12
  • Can you add a ctor with the id as a paramter? – Magnus Jan 19 '22 at 11:12