C
C#5w ago
redmoss

Nice ways to partially serialize and deserialize objects?

Say I've got a class like this:
class Monster
{
public int Id;
public string Name;
public int AttackRating;
public bool Seen;
}
class Monster
{
public int Id;
public string Name;
public int AttackRating;
public bool Seen;
}
In my program, I might have various instances of these in a List that I refer to. When I serialize this list, it saves Id Name and AttackRating but these are instanced in the code so if I change the code, the serialization is now out of date for users who try and load the save when the code has moved on. So really, I just want to serialize the Seen property, because the rest is defined in code by the MonsterFactory. However, I'm not sure how I can deserialise a List<Monster> which was just serialised with the Seen properties serialised only, if that makes sense. The other values are instantiated by the appropriate MonsterFactory in code. Now, I can use [JsonIgnore] to serialize just Seen. However the problem is recreating the list of objects without overwriting the other properties using the MonsterFactory for the rest. Basically I want to be able to create my Monster class again from the factory method, but then deserialize a List<Monster> from file that only stored Seen because it's the only property without [JsonIgnore]. But when I do this, it's going to set all my other properties to null. Any thoughts?
4 Replies
Jimmacle
Jimmacle5w ago
this is a slippery slope, ideally you have classes dedicated to being your serialization models that only contain what you want to serialize then map your actual data to and from those so you'd load the monsters however you do to include their stats, then do a second pass with the data you loaded from the save to update the save-dependent data
redmoss
redmoss5w ago
Ah, yeah, I see. So effectively I'd have a Monster class and a MonsterSerialize that could be a flattened object (since the Monster class may contain nested objects with only particular values I care about) and I use that as an intemediary
Jimmacle
Jimmacle5w ago
right
redmoss
redmoss5w ago
Awesome, thanks for the pointer