0

i am having troubles with serializing a List, each object within the list can have also a List ("links") which should only be serialized by reference. What happens is that the references are on the wrong side, means the Links, contains the actual object information and the parent List contains the reference id.

Find the full code below:

   [Serializable]
   public class Template
   {
        public string Name { get; set; }
        public List<Template> Links { get; set; }

        public Template()
        {
            Links = new List<Template>();
        }
   }



   List<Template> toserialize = new List<Template>();
   toserialize.Add(new JsonTest.Template() { Name = "A" });
   toserialize.Add(new JsonTest.Template() { Name = "B" });
   toserialize.Add(new JsonTest.Template() { Name = "C" });

   toserialize[0].Links.Add(toserialize[1]);
   toserialize[0].Links.Add(toserialize[2]);

   using (FileStream fs = new FileStream(@"C:\Outputtest.json", FileMode.Create))
   using (StreamWriter writer = new StreamWriter(fs))
   using (JsonTextWriter json = new JsonTextWriter(writer))
   {
        JsonSerializer ser = new JsonSerializer()
        {
             TypeNameHandling = TypeNameHandling.Objects,
             ReferenceLoopHandling = ReferenceLoopHandling.Error,
             PreserveReferencesHandling = PreserveReferencesHandling.All,
             NullValueHandling = NullValueHandling.Ignore,
        };
        ser.Serialize(json, toserialize);
        json.Flush();
  }

How can i move the reference id in the right position? You can download the full example here: https://1drv.ms/u/s!AreXFr2kgVXYjacDrPu9rR_7DhE5bg

KR

7
  • Can you share the sample json value itself? Commented May 30, 2018 at 9:54
  • you mean the json file? Commented May 30, 2018 at 9:57
  • Yes... but not the full json file... just the relevant part of it.. Commented May 30, 2018 at 9:57
  • added the json output Commented May 30, 2018 at 10:03
  • Your JSON doesn't match your c# classes. The JSON contains a root property "Items" but the c# class Test contains a root property Templates. Can you provide a minimal reproducible example that actually demonstrates the problem? I tried to deserialize the JSON in the question with the classes shown, but nothing was deserialized: dotnetfiddle.net/tRmOdp Commented May 31, 2018 at 0:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.