将json反序列化为具有默认私有构造函数的类的C#对象

Sha*_*pta 16 c# serialization json json.net

我需要将json反序列化为以下类.

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

    private Test()
    {
        //NOTHING TO INITIALIZE
    }

    public Test(string prop)
    {
        Property = prop;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以创建一个Test实例

var instance = new Test("Instance");
Run Code Online (Sandbox Code Playgroud)

考虑我的json之类的东西

"{  "Property":"Instance" }"
Run Code Online (Sandbox Code Playgroud)

我如何创建Test类的对象,因为我的默认构造函数是私有的,我得到的对象是Property为NULL

我正在使用Newtonsoft Json解析器.

Bri*_*ers 36

您可以通过使用[JsonConstructor]属性标记Json.Net来调用私有构造函数:

[JsonConstructor]
private Test()
{
    //NOTHING TO INITIALIZE
}
Run Code Online (Sandbox Code Playgroud)

请注意,在调用构造函数后,序列化程序仍将使用公共setter填充对象.

编辑

另一种可能的选择是使用以下ConstructorHandling设置:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};

Test t = JsonConvert.DeserializeObject<Test>(json, settings);
Run Code Online (Sandbox Code Playgroud)

  • 如果您要序列化的对象位于库/程序集中,而您不希望引入第三方依赖项(包括对Json.Net的依赖项...),则第二个选项是最佳选项. (4认同)