Tôi có một loại mà tôi không kiểm soát với nhiều nhà xây dựng, tương đương với này một:Không thể deserialize lớp học với nhiều nhà xây dựng với Json.NET
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; }
}
}
Bây giờ khi tôi cố gắng deserialize nó, riêng constuctor parameterless được gọi và thuộc tính không bao giờ được thiết lập. Các thử nghiệm:
[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);
}
cho đầu ra sau đây:
We don't want this one to be called.
Expected: "test"
But was: null
Làm thế nào tôi có thể sửa chữa nó, mà không thay đổi định nghĩa của MyClass
? Ngoài ra, loại này là một chìa khóa sâu trong định nghĩa của các đối tượng mà tôi thực sự cần phải serialize.
Cảm ơn, không may, như tôi đã viết trong câu hỏi, tôi không thể thay đổi lớp. – Grzenio
Sau đó, tôi nghĩ rằng bạn cần tạo một CustomJsonConverter. Đây không phải là điều tôi đã làm tôi sợ. –
Thử tìm tại đây: http://stackoverflow.com/a/8312048/234415 –