Deserialization of self-referencing properties does not work

前端 未结 3 431
日久生厌
日久生厌 2020-11-30 15:00

I have this object with a Parent property that reference another object of the same type:

[JsonObject(IsReference = true)]
class Group
{
    public strin         


        
相关标签:
3条回答
  • 2020-11-30 15:35

    To expand on James's answer, you can fix this issue by providing a parameterless (default) constructor for Json.Net to use. It can be private if you want, so long as you also mark it with a [JsonConstructor] attribute.

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

    This arrangement allows Json.Net to create the object without needing all the information up front; it can then use the public properties to fill things in afterward.

    Fiddle: https://dotnetfiddle.net/QfqV43

    0 讨论(0)
  • 2020-11-30 15:38

    Using references doesn't work with objects that only have constructors with parameters.

    Json.NET has to deserialize all the child values before it creates the parent, it needs those values to pass to the constructor, so there is no valid parent reference to assign to the child.

    0 讨论(0)
  • 2020-11-30 15:58

    Another way, i found, by being very stubborn is creating a two phase deserialization,
    as i describe in the following Deserializing Circular References by Two-Phase deserialization

    in general, i create two IContractResolvers, One is used to deserialize only the properties of the Constructor (in case it has parameters).

    and in the second phase, I populate the object using regular ContractResolver.

    0 讨论(0)
提交回复
热议问题