ConstructorHandling setting

April 6, 2024 ยท View on GitHub

This sample uses the Argon.ConstructorHandling setting to successfully deserialize the class using its non-public constructor.

public class Website
{
    public string Url { get; set; }

    // ReSharper disable once UnusedMember.Local
    Website()
    {
    }

    public Website(Website website) =>
        Url = website.Url;
}

snippet source | anchor

var json = "{'Url':'http://www.google.com'}";

try
{
    JsonConvert.DeserializeObject<Website>(json);
}
catch (Exception exception)
{
    Console.WriteLine(exception.Message);
    // Value cannot be null.
    // Parameter name: website
}

var website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
{
    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});

Console.WriteLine(website.Url);
// http://www.google.com

snippet source | anchor