Deserialize json into C# object for class which has default private constructor

前端 未结 4 1645
误落风尘
误落风尘 2020-12-14 19:03

I need to deserialize json for following class.

public class Test
{
    public string Property { get; set; }

    private Test()
    {
        //NOTHING TO I         


        
4条回答
  •  春和景丽
    2020-12-14 19:36

    You can make Json.Net call the private constructor by marking it with a [JsonConstructor] attribute:

    [JsonConstructor]
    private Test()
    {
        //NOTHING TO INITIALIZE
    }
    

    Note that the serializer will still use the public setters to populate the object after calling the constructor.

    EDIT

    Another possible option is to use the ConstructorHandling setting:

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
    };
    
    Test t = JsonConvert.DeserializeObject(json, settings);
    

提交回复
热议问题