JSON.net: how to deserialize without using the default constructor?

后端 未结 5 1986
天涯浪人
天涯浪人 2020-11-22 07:21

I have a class that has a default constructor and also an overloaded constructor that takes in a set of parameters. These parameters match to fields on the object and are a

5条回答
  •  借酒劲吻你
    2020-11-22 07:48

    The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

    Admittedly, this solution is rather very limited to specific cases.

    internal Result() { }
    
    public Result(int? code, string format, Dictionary details = null)
    {
        Code = code ?? ERROR_CODE;
        Format = format;
    
        if (details == null)
            Details = new Dictionary();
        else
            Details = details;
    }
    

提交回复
热议问题