C#C
C#2y 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;
}


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?
Was this page helpful?