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)
| 归档时间: |
|
| 查看次数: |
13888 次 |
| 最近记录: |