ConstructorHandling setting |
This sample uses the ConstructorHandling setting to successfully deserialize the class using its non-public constructor.
public class Website { public string Url { get; set; } private Website() { } public Website(Website website) { if (website == null) { throw new ArgumentNullException(nameof(website)); } Url = website.Url; } }
string json = @"{'Url':'http://www.google.com'}"; try { JsonConvert.DeserializeObject<Website>(json); } catch (Exception ex) { Console.WriteLine(ex.Message); // Value cannot be null. // Parameter name: website } Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }); Console.WriteLine(website.Url); // http://www.google.com