Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- public class Circulair1 {
- public string Naam => "Ik ben circulair 1";
- public Circulair2 instantieVan2;
- public void ZetInstantieVan2 (Circulair2 inst2) {
- instantieVan2 = inst2;
- }
- }
- public class Circulair2 {
- public string Naam => "Ik ben circulair 2";
- public Circulair1 instantieVan1;
- public Circulair2(Circulair1 inst1){
- instantieVan1 = inst1;
- }
- }
- public class Program
- {
- public static void Main()
- {
- /* Preparatie */
- Circulair1 Circ1 = new();
- Circulair2 Circ2 = new(Circ1);
- Circ1.ZetInstantieVan2(Circ2);
- /* Circulair zonder instellingen */
- //JObject pogingMetCirculair = JObject.FromObject(Circ1); //JsonSerializerException: Self referencing loop detected
- //JObject pogingMetCirculair2 = JObject.FromObject(Circ2);
- /* Instellingen */
- var JSS = new JsonSerializer {
- NullValueHandling = NullValueHandling.Ignore,
- ReferenceLoopHandling = ReferenceLoopHandling.Ignore //,
- //PreserveReferencesHandling = PreserveReferencesHandling.Objects
- };
- /* Circulair met deze instellingen */
- JObject pogingMetSettingsCirculair = JObject.FromObject(Circ1, JSS);
- JObject pogingMetSettingsCirculair2 = JObject.FromObject(Circ2, JSS);
- Console.WriteLine(pogingMetSettingsCirculair.ToString());
- Console.WriteLine(pogingMetSettingsCirculair2.ToString());
- /* -- Output
- {
- "instantieVan2": {
- "Naam": "Ik ben circulair 2"
- },
- "Naam": "Ik ben circulair 1"
- }
- {
- "instantieVan1": {
- "Naam": "Ik ben circulair 1"
- },
- "Naam": "Ik ben circulair 2"
- }
- -- Gedrag
- Json.NET will ignore objects in reference loops and not serialize them.
- The first time an object is encountered >>it will be serialized<< as usual but if the object is encountered
- as a child object of itself the serializer will skip serializing it.
- */
- /* Nieuwe instelling met serialize */
- var JSS2 = new JsonSerializer {
- NullValueHandling = NullValueHandling.Ignore,
- ReferenceLoopHandling = ReferenceLoopHandling.Serialize
- };
- //JObject pogingMetSettingsSerializeCirculair = JObject.FromObject(Circ1, JSS2); // stack overflow
- //JObject pogingMetSettingsSerializeCirculair2 = JObject.FromObject(Circ2, JSS2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment