I recieve a JSON file from database in the c# client. Then I deserialize this JSON to an object of a class. Now when updated JSON arrives from database afterwards, what I want is to somehow replace every data of the old object with a new one. I need this because rest of code has many references to the old object and its properties, so simply assigning new object to old one would not work as all references would be lost. Is the only solution here performing a deep copy of the object? If so what is a best way to do this? Honestly I never needed anything like that for many years, I am quite surprised that this issue arise now but the reason is probably that I recieve dataj from database in JSON and have to someho deserialize it into new object.
The only solution I tried is manual copying of the fields betwee new and old object but its a pain to keep it updated whenever I change the class structure which I do a lot
CodePudding user response:
SUGGESTION: Create a wrapper class with a property for the actual data. Pass a reference to your wrapper; read or update the data at will. The "reference" is unchanged; everybody will automatically "see" any data updates.
public class MyWrapper
{
public MyDataClass MyData { get; set; }
}
public class SomeClass
{
public void SomeMethod ()
{
// Instantiate your data
var wrapper = new MyWrapper();
wrapper.MyData = ReadFromDbAndDeserialize();
// And pass it to other client(s)
SomeOtherMethod(wrapper);
}
}
CodePudding user response:
You could use Automapper to create deep copies automatically. You would need to set up some mappings manually though but it's less painful anyway.