C# 无法使用Json.NET反序列化具有多个构造函数的类
我有一个我不能用多个构造函数控制的类型,相当于这个类型:C# 无法使用Json.NET反序列化具有多个构造函数的类,c#,.net,json,json.net,C#,.net,Json,Json.net,我有一个我不能用多个构造函数控制的类型,相当于这个类型: public class MyClass { private readonly string _property; private MyClass() { Console.WriteLine("We don't want this one to be called."); } public MyClass(strin
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<MyClass>(output);
Assert.AreEqual(expected.Property, actual.Property);
}
如何在不更改
MyClass
定义的情况下修复它?此外,在我真正需要序列化的对象的定义中,这种类型是一个很重要的元素。尝试将[JsonConstructor]
属性添加到反序列化时要使用的构造函数中
在类中更改此属性:
[JsonConstructor]
public MyClass(string property)
{
_property = property;
}
我刚刚试过,你的测试通过了:-)
如果您无法进行此更改,那么我想您需要创建一个CustomJsonConverter
。也许会有帮助
下面是一个有用的链接,用于创建
CustomJsonConverter
:谢谢,不幸的是,正如我在问题中所写,我无法更改类。然后我认为您需要创建CustomJsonConverter。恐怕这不是我做过的事。试着看看这里:
[JsonConstructor]
public MyClass(string property)
{
_property = property;
}