2017-07-07 54 views
0

我正在使用Newtonsoft庫進行序列化和反序列化json對象。 參考代碼如下:JSON使用Newtonsoft反序列化字符串值列表<T> - 構造函數arg在C中爲null#

public abstract class BaseNode 
{ 
    [JsonConstructor] 
    protected BaseNode(string [] specifications) 
    { 
     if (specifications == null) 
     { 
      throw new ArgumentNullException(); 
     } 
     if (specifications.Length == 0) 
     { 
      throw new ArgumentException(); 
     } 

     Name = specifications[0]; 
     Identifier = specifications[1]; 
     //Owner = specifications[2]; 
    } 

    public string Name{ get; protected set; } 
    public string Identifier { get; protected set; } 
    public string Owner { get; protected set; } 
} 


public class ComputerNode: BaseNode 
{ 
    [JsonConstructor] 
    public ComputerNode(string[] specifications):base(specifications) 
    { 
     Owner = specifications[2]; 
    } 
} 

序列化工作正常,我可以保存JSON文件中的格式的數據。我將一個ComputerNode對象的列表存儲在一個文件中。文件的讀/寫操作 以下代碼:

public class Operation<T> 
{ 
    public string path; 

    public Operation() 
    { 
     var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt"); 

     if (File.Exists(path) == false) 
     { 
      using (File.Create(path)) 
      { 
      } 
     } 
     this.path = path; 
    } 

    public void Write(string path, List<T> nodes) 
    { 
     var ser = JsonConvert.SerializeObject(nodes); 

     File.WriteAllText(path, ser); 
    } 

    public List<T> Read(string path) 
    { 
     var text = File.ReadAllText(path); 

     var res = JsonConvert.DeserializeObject<List<T>>(text); 
     return res; 
    } 

} 

預期的文件中讀取結果應該是存儲在文件中ComputerNode對象的列表。 但是,雖然反序列化 - 創建ComputerNode的對象,正確的構造函數被調用,但參數(字符串[]規範)爲空。

有沒有更好的方法來使用它。

請不要建議改變BaseNode.cs或ComputerNode.cs

感謝的建議...

正確答案

新的Json構造覆蓋。在BaseNode.cs

[JsonConstructor] 
    public BaseNode(string Owner, string Name, string Identifier) 
    { 
     this.Name = Name; 
     this.Identifier = Identifier; 
    } 

和 重寫一個JSON構造 - ComputerNode.cs

[JsonConstructor] 
    public ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier) 
    { 
     this.Owner = Owner; 
    } 
+0

你的JSON是什麼樣的?我不明白爲什麼你需要在反序列化一個井結構JSON對象時將這些傳遞給構造函數。它應該只是像你期望的那樣填充屬性。 – Skintkingle

+0

[ { 「名稱」: 「傑克」, 「標識」: 「123345」, 「所有者」: 「CiiW」 }, { 「名稱」: 「嘀嘀」, 「標識」:「 1dd123345「, 」Owner「:」C12W「 } ] – JayeshThamke

+0

對不起,它沒有在SO編輯器中添加縮進。 – JayeshThamke

回答

0

如果您運行實踐

var ser = JsonConvert.SerializeObject(nodes); 
File.WriteAllText(path, ser); 

其中節點是一個List < T>

然後

var text = File.ReadAllText(path); 
var res = JsonConvert.DeserializeObject<List<T>>(text); 

其中RES是一個列表< T>

按照JsonConstructor文檔:http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConstructorAttribute.htm

指示JsonSerializer反序列化對象時使用的指定構造。

沒有說,會有一個與要反序列化的字符串相關的構造函數參數。

其實構造您指定([JsonConstructor])試圖重寫反序列化的結果,與總是空參數

你的情況,你應該有

[JsonConstructor] 
protected BaseNode() 
{ 

} 

以避免與交互的構造反序列化。

恕我直言,反序列化器絕不會(根據文檔)給構造函數一個參數。

相關問題