Search code examples
c#datacontractserializer

DataContractSerializer: can't deserialize because of changed property type


I have a property named Lender which previously was a string, and has since changed to the complex type Lender. I thought an implicit operator overload would resolve the transformation from a string to an object, but it doesn't, and deserialization fails.

Can I fix this in any way, or must I refactor my code for backwards compatibility?

Before:

class AnObject {
  string Lender { get; set; }
}

After:

class AnObject {
  Lender Lender { get; set; }
}

class Lender {
  public string Name { get; set; } // Previously the string property on AnObject.

  public static implicit operator Lender(string name) {
    return new Lender(name);
  }
}

Exception:

Error in line 1 position 249. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.


Solution

  • I had to "transition" the XML into the new format by replacing the text nodes under the Lender node with the Lender object serialized using the DataContract serializer.