static void Intermediate_4_CircularRecursion() { ConsoleTitle("SECTION: Circular Recursion"); PersonV4 p1 = new PersonV4("Bob"); PersonV4 p2 = new PersonV4("Janet", p1); p1.SetParent(p2); PersonV4 p3 = new PersonV4("Suzette", partner: p2); List <PersonV4> pList1 = new List <PersonV4> { p1, p2, p3 }; JsonSerializerSettings settings1 = new JsonSerializerSettings { ContractResolver = new PrivateSetResolver(), PreserveReferencesHandling = PreserveReferencesHandling.Objects }; string json1 = JsonConvert.SerializeObject(pList1, Formatting.Indented, settings: settings1); List <PersonV4> pList2 = JsonConvert.DeserializeObject <List <PersonV4> >(json1, settings: settings1); PersonV4 np1a = pList2[0]; PersonV4 np2a = pList2[1]; PersonV4 np3a = pList2[2]; List <PersonV4b> pList3 = JsonConvert.DeserializeObject <List <PersonV4b> >(json1, settings: settings1); PersonV4b np1b = pList3[0]; PersonV4b np2b = pList3[1]; PersonV4b np3b = pList3[2]; DrawJson(json1, "json1"); Console.WriteLine("\n Initial Data:"); pList1.ForEach(p => Console.WriteLine($" -> {p}")); Console.WriteLine(" Deserialized Data v1:"); pList2.ForEach(p => Console.WriteLine($" -> {p}")); Console.WriteLine(" Deserialized Data v2:"); pList3.ForEach(p => Console.WriteLine($" -> {p}")); Console.WriteLine("\n Expected Answers (pre-serialization):"); AreTheseEqual(p1, p2.Parent); AreTheseEqual(p2, p3.Partner); AreTheseEqual(p2, p1.Parent); Console.WriteLine(" Actual Answers (post-serialization) (expect errors):"); AreTheseEqual(np1a, np2a.Parent); AreTheseEqual(np2a, np3a.Partner); AreTheseEqual(np2a, np1a.Parent); Console.WriteLine(" Desired Answers (post-serialization) -- w/ empty default constructor:"); AreTheseEqual(np1b, np2b.Parent); AreTheseEqual(np2b, np3b.Partner); AreTheseEqual(np2b, np1b.Parent); }
public void SetPartner(PersonV4 partner) => this.Parent = partner;
public void SetParent(PersonV4 parent) => this.Parent = parent;
public PersonV4(string name, PersonV4 parent = null, PersonV4 partner = null) { this.Name = name; this.Parent = parent; this.Partner = partner; }