无法在Json.NET中反序列化带有多个构造函数的类

本文关键字:构造函数 反序列化 Json NET | 更新日期: 2023-09-27 18:12:24

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

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

给出如下输出:

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

我如何修复它,而不改变MyClass的定义?而且,这种类型是我真正需要序列化的对象定义中的一个关键。

无法在Json.NET中反序列化带有多个构造函数的类

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

在你的类中修改这个属性:

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

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

如果你不能做这个改变,那么我猜你需要创建一个CustomJsonConverter。http://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm和如何在JSON中实现自定义JsonConverter。. NET反序列化基类对象的列表?可能会有帮助。

这里有一个创建CustomJsonConverter的有用链接:https://stackoverflow.com/a/8312048/234415