No need to create Serializer settings and assign ConstructorHandling here. Remember to specify the [JsonConstructor] attribute for the private constructor. I have a similar case with the abstract BaseNode.cs and its specific implementation of ComputerNode.cs. You can create classes, copy / paste the code below and conduct an experiment.
public abstract class BaseNode { [JsonConstructor] // ctor used when Json Deserializing protected BaseNode(string Owner, string Name, string Identifier) { this.Name = Name; this.Identifier = Identifier; } // ctor called by concrete class. protected BaseNode(string [] specifications) { if (specifications == null) { throw new ArgumentNullException(); } if (specifications.Length == 0) { throw new ArgumentException(); } Name = specifications[0]; Identifier = specifications[1]; } public string Name{ get; protected set; } public string Identifier { get; protected set; } } public class ComputerNode: BaseNode { public string Owner { get; private set; } [JsonConstructor] // not visible while creating object from outside and only used during Json Deserialization. private ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier) { this.Owner = Owner; } public ComputerNode(string[] specifications):base(specifications) { Owner = specifications[2]; } }
For JSon, reading and writing code helps -
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, Formatting.Indented); File.WriteAllText(path, ser); } public List<T> Read(string path) { var text = File.ReadAllText(path); var res = JsonConvert.DeserializeObject<List<T>>(text); return res; } }
All the best!
Jayeshthamke
source share