I have this object with the Parent property, which refers to 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 causes json to look like this:
{ "$id": "1", "Name": "Parent", "Children": [ { "$id": "2", "Name": "Child", "Children": [], "Parent": { "$ref": "1" } } ], "Parent": null }
But deserialization does not work. The parent property is returned null.
The test is as follows:
[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!
source share