2014-07-10 5 views
10

여러 생성자와 클래스를 직렬화 할 수 없습니다 나는 이것에 동일한 나는 여러 생성자와 통제하지 않는 유형이 : 나는, 민간를 직렬화 할 때 이제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; } 
     } 

    } 

을 매개 변수없는 constuctor가 호출되고 속성이 설정되지 않습니다. 테스트 :

We don't want this one to be called. 

    Expected: "test" 
    But was: null 

가 어떻게 고칠 수, MyClass의 정의를 변경하지 않고 :

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

다음과 같은 출력을 제공합니다? 또한이 유형은 필자가 실제로 직렬화 할 필요가있는 객체 정의의 핵심이다.

답변

5

역 직렬화시 사용할 생성자에 [JsonConstructor] 속성을 추가해보십시오.

변경 클래스에서이 속성 :

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

나는 단지 및 테스트는 다음이 변경을 할 수없는 경우 당신이 필요 거라고 생각

:-) 전달 시도 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?이 도움이 될 수 있습니다. 내가 질문에 쓴 https://stackoverflow.com/a/8312048/234415

+0

감사합니다, 불행하게도, 내가 클래스를 변경할 수 없습니다 :

는 여기 CustomJsonConverter 작성에 대한 유용한 링크입니다. – Grzenio

+0

그러면 CustomJsonConverter를 만들어야한다고 생각합니다. 이 일은 제가 한 일이 아닙니다. –

+0

여기를 찾으십시오. http://stackoverflow.com/a/8312048/234415 –