我正在使用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;
}
你的JSON是什麼樣的?我不明白爲什麼你需要在反序列化一個井結構JSON對象時將這些傳遞給構造函數。它應該只是像你期望的那樣填充屬性。 – Skintkingle
[ { 「名稱」: 「傑克」, 「標識」: 「123345」, 「所有者」: 「CiiW」 }, { 「名稱」: 「嘀嘀」, 「標識」:「 1dd123345「, 」Owner「:」C12W「 } ] – JayeshThamke
對不起,它沒有在SO編輯器中添加縮進。 – JayeshThamke