I have this object with a Parent property that reference another object of the same type:
[JsonObject(IsReference = true)]
class Group
{
public string Name { get; set; }
public Group(string name)
{
Name = name;
Children = new List<Group>();
}
public IList<Group> Children { get; set; }
public Group Parent { get; set; }
public void AddChild(Group child)
{
child.Parent = this;
Children.Add(child);
}
}
Serialization works fine and results in json looking like this:
{
"$id": "1",
"Name": "Parent",
"Children": [
{
"$id": "2",
"Name": "Child",
"Children": [],
"Parent": {
"$ref": "1"
}
}
],
"Parent": null
}
But deserialization doesn't work. The Parent property comes back null.
A test looks like this:
[Test]
public void Test()
{
var child = new Group("Child");
var parent = new Group("Parent");
parent.AddChild(child);
var json = JsonConvert.SerializeObject(parent, Formatting.Indented);
Debug.WriteLine(json);
var deserializedParent = (Group) JsonConvert.DeserializeObject(json, typeof(Group));
Assert.IsNotNull(deserializedParent.Children.First().Parent);
}
What am I doing wrong? Any help appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…