我正在使用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