无法反序列化与多个构造函数的类与Json.NET [英] Unable to deserialize classes with multiple constructors with Json.NET

查看:141
本文介绍了无法反序列化与多个构造函数的类与Json.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a type that I don't control with multiple constructors, equivalent to this one:

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

    }

当我尝试反序列化

现在它,私人参constuctor被调用,该属性从未设置。测试:

Now when I try to deserialize it, the private parameterless constuctor is called and the property is never set. The test:

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



给出了以下的输出:

gives the following output:

We don't want this one to be called.

  Expected: "test"
  But was:  null



我怎么能解决这个问题,在不改变 MyClass的的定义是什么?此外,这种类型是我真正需要序列化对象的定义键深。

How can I fix it, without changing the definition of MyClass? Also, this type is a key deep in the definition of the objects that I really need to serialize.

推荐答案

尝试添加< 。code> [JsonConstructor] 属性您要反序列化时使用的构造

Try adding the [JsonConstructor] attribute to the constructor you want to use when deserializing.

在你的类更改此属性:

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



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

I have just tried it and your test passes :-)

如果你不能让这种变化那么我想你需要创建一个 CustomJsonConverter http://james.newtonking.com/json/help /index.html?topic=html/CustomJsonConverter.htm 并的如何实现自定义JsonConverter在JSON.NET反序列化基类对象可以帮助的List。

If you can't make this change then I guess you'd need to create a CustomJsonConverter. http://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm and How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects might help.

下面是创建 CustomJsonConverter 有用的链接:的http://计算器.COM / A /234415分之8312048

Here is a useful link for creating a CustomJsonConverter: http://stackoverflow.com/a/8312048/234415

这篇关于无法反序列化与多个构造函数的类与Json.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆