2017-07-07 52 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() 
{ 

} 

以避免与交互的构造反序列化。

恕我直言,反序列化器绝不会(根据文档)给构造函数一个参数。

相关问题