问题
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.
回答1:
Try adding the [JsonConstructor]
attribute to the constructor you want to use when deserializing.
Change this property in your class:
[JsonConstructor]
public MyClass(string property)
{
_property = property;
}
I have just tried it and your test passes :-)
If you can't make this change then I guess you'd need to create a CustomJsonConverter
. http://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm and How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? might help.
Here is a useful link for creating a CustomJsonConverter
: https://stackoverflow.com/a/8312048/234415
来源:https://stackoverflow.com/questions/24678734/unable-to-deserialize-classes-with-multiple-constructors-with-json-net