Hi,
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();
}
A full example you can download
here.
Incorrect Json:
{
"$id": "1",
"$values": [{
"$id": "2",
"$type": "JsonTest.Template, JsonTest",
"Name": "A",
"Links": {
"$id": "3",
"$values": [{
"$id": "4",
"$type": "JsonTest.Template, JsonTest",
"Name": "B",
"Links": {
"$id": "5",
"$values": []
}
},
{
"$id": "6",
"$type": "JsonTest.Template, JsonTest",
"Name": "C",
"Links": {
"$id": "7",
"$values": []
}
}]
}
},
{
"$ref": "4"
},
{
"$ref": "6"
}]
}
How it should look like:
{
"$id": "1",
"$values": [{
"$id": "2",
"$type": "JsonTest.Template, JsonTest",
"Name": "A",
"Links": {
"$id": "3",
"$values": [{"$ref":"4"}, {"$ref":"6"}]
}
},
{
"$id": "4",
"$type": "JsonTest.Template, JsonTest",
"Name": "B"
},
{
"$id": "6",
"$type": "JsonTest.Template, JsonTest",
"Name": "C"
}]
}
KR Manu
What I have tried:
I have tried all possible JsonSerializer Configurations without success.