I've a simple relational model with a Parent and Child relation as follows:
public class Parent
{
public Parent(int id)
{
Id = id;
}
public int Id { get; private set; }
public IList<Child> Children { get; set; } = new List<Child>();
}
public class Child
{
public Parent Parent { get; set; }
}
I create a small object graph consisting of a list of two children who share the same parent:
var parent = new Parent(1);
var child1 = new Child {Parent = parent};
var child2 = new Child {Parent = parent};
parent.Children.Add(child1);
parent.Children.Add(child2);
var data = new List<Child> {child1, child2};
Next, I serialize this using SerializeObject
:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data, Formatting.Indented, settings);
As far I can see, the resulting json looks fine:
{
"$id": "1",
"$values": [
{
"$id": "2",
"Parent": {
"$id": "3",
"Id": 1,
"Children": {
"$id": "4",
"$values": [
{
"$ref": "2"
},
{
"$id": "5",
"Parent": {
"$ref": "3"
}
}
]
}
}
},
{
"$ref": "5"
}
]
}
However, when I deserialize the json I don't get the expected object because for the second child the Parent property is null, causing the second assertion to fail:
var data2 = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<Child>>(json, settings);
Debug.Assert(data2[0].Parent != null);
Debug.Assert(data2[1].Parent != null);
Without the constructor of Parent
this problem does not occur and the Parent property of the second child has the expected value.
Any ideas what this could be?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…