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

查看:450
本文介绍了无法与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.

推荐答案

尝试添加 [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和<一href="http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base">How实现自定义JsonConverter在JSON.NET反序列化基类对象的列表可能的帮助。

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:// stackoverflow.com/a/8312048/234415

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

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

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