The desalization of self-reference properties does not work

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!

+3
source share
2 answers

Using links does not work with objects that have only constructors with parameters.

Json.NET must deserialize all child values ​​before it creates the parent element, it needs to pass these values ​​to the constructor, so there is no valid parent link to assign the child element.

+4
source

To extend James's answer, you can fix this problem by providing a parameterless constructor (default) to use Json.Net. It can be closed if you want, if you also mark it with the [JsonConstructor] attribute.

 [JsonObject(IsReference = true)] class Group { ... [JsonConstructor] private Group() { } public Group(string name) { Name = name; Children = new List<Group>(); } ... } 

This layout allows Json.Net to create an object without prior information; he can then use public properties to populate things later.

Fiddle: https://dotnetfiddle.net/QfqV43

+2
source

All Articles