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