15

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

    }

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

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.

0

1 Answer 1

16

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

Change this property in your class:

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

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

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.

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, unfortunately, as I wrote in the question, I can't change the class.
Then I think you need to create a CustomJsonConverter. This is not something I've done I'm afraid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.