2014-07-10 16 views
10

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.

Trả lời

5

Thử thêm thuộc tính [JsonConstructor] vào hàm tạo mà bạn muốn sử dụng khi deserializing.

Thay đổi thuộc tính này trong lớp học của bạn:

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

Tôi vừa thử nó và thử nghiệm của bạn đi :-)

Nếu bạn không thể thực hiện thay đổi này sau đó tôi đoán bạn sẽ cần phải tạo một CustomJsonConverter. http://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? có thể hữu ích.

Dưới đây là một liên kết hữu ích cho việc tạo ra một CustomJsonConverter: https://stackoverflow.com/a/8312048/234415

+0

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

+0

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ợ. –

+0

Thử tìm tại đây: http://stackoverflow.com/a/8312048/234415 –

Các vấn đề liên quan