【问题标题】:Unable to deserialize classes with multiple constructors with Json.NET [duplicate]无法使用 Json.NET 反序列化具有多个构造函数的类 [重复]
【发布时间】:2014-07-10 14:07:27
【问题描述】:

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

    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 定义的情况下修复它?此外,这种类型是我真正需要序列化的对象定义中的一个关键。

【问题讨论】:

    标签: c# .net json json.net


    【解决方案1】:

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

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

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

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

    如果您无法进行此更改,那么我想您需要创建一个CustomJsonConverterhttp://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htmHow to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? 可能会有所帮助。

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

    【讨论】:

    • 谢谢,不幸的是,正如我在问题中所写,我无法更改课程。
    • 那我觉得你需要创建一个CustomJsonConverter。恐怕这不是我做过的事情。
    猜你喜欢
    • 2013-04-02
    • 2023-03-24
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多