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

  • Can you share the sample json value itself? – Chetan May 30 '18 at 09:54
  • you mean the json file? –  May 30 '18 at 09:57
  • Yes... but not the full json file... just the relevant part of it.. – Chetan May 30 '18 at 09:57
  • added the json output –  May 30 '18 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 [mcve] that actually demonstrates the problem? I tried to deserialize the JSON in the question with the classes shown, but nothing was deserialized: https://dotnetfiddle.net/tRmOdp – dbc May 31 '18 at 00:50
  • But possibly related: [JSON.NET StackOverflowException while serialization](https://stackoverflow.com/q/41828014/3744182). – dbc May 31 '18 at 00:51
  • Added the full example including project to download –  May 31 '18 at 12:11

0 Answers0