1

Closed

Protected ctor does not get called

description

In the example below, why does the public ctor get picked instead of the default protected ctor?
This will fail because of this - it will succeed if the default ctor gets picked


void Main()
{
JsonConvert.DeserializeObject<List>("[{\"id\":2}]").Dump();
}

public class Tagged : Tag
{
    protected Tagged() : base() { }

    public Tagged(Tag tagDefinition)
    {
        Id = tagDefinition.Id;
    }
}
public abstract class Tag
{
    public int Id { get; set; }
}
Closed Jan 30, 2013 at 10:09 AM by JamesNK
Because Json.NET defaults to using public. Read the documentation if you want to see how to change that.

comments

georgiosd wrote Feb 13, 2013 at 6:34 PM

The only thing I could find in the docs is JsonConstructor which only allows to do it on a per-object basis.

I'd like JSON.NET to use the default ctor in all cases, regardless of its visibility - is this possible to specify?

georgiosd wrote Feb 13, 2013 at 6:36 PM

Never mind, just found ConstructorHandling.AllowNonPublicDefaultConstructor