无法使用Json.NET反复使用多个构造函数对类进行反序列化

我有一个我不用多个构造函数控制的类型,相当于这个:

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; } } } 

现在,当我尝试反序列化它时,将调用私有无参数构造函数,并且永远不会设置该属性。 考试:

  [Test] public void MyClassSerializes() { MyClass expected = new MyClass("test"); string output = JsonConvert.SerializeObject(expected); MyClass actual = JsonConvert.DeserializeObject(output); Assert.AreEqual(expected.Property, actual.Property); } 

给出以下输出:

 We don't want this one to be called. Expected: "test" But was: null 

如何在不改变MyClass定义的情况下修复它? 此外,这种类型是我真正需要序列化的对象定义的关键。

尝试将[JsonConstructor]属性添加到反序列化时要使用的构造函数。

在您的class级中更改此属性:

 [JsonConstructor] public MyClass(string property) { _property = property; } 

我刚尝试过,你的测试通过了:-)

如果您无法进行此更改,那么我猜您需要创建一个CustomJsonConverterhttp://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm以及如何在JSON.NET中实现自定义JsonConverter来反序列化基类对象列表? 可能有帮助。

以下是创建CustomJsonConverter的有用链接: https : CustomJsonConverter