无法使用Json.NET反序列化具有多个构造函数的类

15

我有一个类型,有多个构造函数,但我无法控制它,其中一个构造函数如下:

    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的定义?此外,这种类型是我真正需要序列化的对象定义中的一个重要部分。

1个回答

16

尝试在要用于反序列化的构造函数上添加[JsonConstructor]属性。

更改您的类中的此属性:

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

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

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

这是一个有用的链接,可以帮助您创建CustomJsonConverterhttps://dev59.com/Bmsy5IYBdhLWcg3w4x_c#8312048


谢谢,不幸的是,正如我在问题中写的那样,我不能改变这个类。 - Grzenio
那么我认为你需要创建一个CustomJsonConverter。很抱歉,这不是我做过的事情。 - Tom Chantler
试着看这里:https://dev59.com/Bmsy5IYBdhLWcg3w4x_c#8312048 - Tom Chantler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接