I have a type that I don't control with multiple constructors, equivalent to this one:
public class MyClass
{
private readonly string _property;
private MyClass()
{
Console.WriteLine("We don't want this one to be called.");
}
public MyClass(string property)
{
_property = property;
}
public MyClass(object obj) : this(obj.ToString()) {}
public string Property
{
get { return _property; }
}
}
Now when I try to deserialize it, the private parameterless constuctor is called and the property is never set. The test:
[Test]
public void MyClassSerializes()
{
MyClass expected = new MyClass("test");
string output = JsonConvert.SerializeObject(expected);
MyClass actual = JsonConvert.DeserializeObject<MyClass>(output);
Assert.AreEqual(expected.Property, actual.Property);
}
gives the following output:
We don't want this one to be called.
Expected: "test"
But was: null
How can I fix it, without changing the definition of MyClass
? Also, this type is a key deep in the definition of the objects that I really need to serialize.