I had a class that I was regularly serializing and deserializing. One of its fields used to be a string to represent a road, but has since been changed to its own class.
class Foo
{
public string RoadRef;
}
Has now been changed to:
class Foo
{
public Road RoadRef;
}
class Road
{
public Road(string val)
{
Lane = val[0];
Number = int.Parse(val.Substring(1));
}
public char Lane;
public int Number = 1;
}
Now I'm getting errors when I try to deserialize from strings that were serialized with the old version of the class. I have a lot of old serialized files that I don't want to go back and reserialize to the new format, especially since changes like this will likely happen again.
I should be able to specify a custom method to Deserialize (and Serialize) for JsonConvert.Deserialize
right?
Is there a better approach to deal with this problem?
The closest I've got so far is adding a [JsonConstructor]
attribute above the constructor as suggested here, but it didn't help the deserializing crashes.
The original JSON looks like this: {"RoadRef":"L1"} It throws this exception:
Newtonsoft.Json.JsonSerializationException: 'Error converting value "L1" to type 'Road'. Path 'RoadRef', line 1, position 15.'
ArgumentException: Could not cast or convert from System.String to Vis_Manager.Road.