[英]How to get deserialized C# record with default constructor parameter with Newton as with System.Text.Json?
假设一开始我有一个只有一个参数“int no”的记录。 后来,随着程序的发展,添加了具有默认值的新参数,结果:
record SimpleRecord(int no, string paramStr = "New param that did not existed");
现在用两个不同的库解析以前保存的 json:
string jsonText = "{\"no\":10}";
SimpleRecord? parsedJson1 = System.Text.Json.JsonSerializer.Deserialize<SimpleRecord>(jsonText);
SimpleRecord? parsedJson2 = Newtonsoft.Json.JsonConvert.DeserializeObject<SimpleRecord>(jsonText);
我希望解析记录为 System.Text.Json -> {SimpleRecord { no = 10, paramStr = New param that didn't exist }} Newton 解析记录是 {SimpleRecord { no = 10, paramStr = }}
paramStr 为空。 如何使用 Newton 库实现与 System.Text.Json 相同的结果? (我有牛顿的现有项目,所以试图避免重写)。
我更喜欢为 Newtonsoft.Json 添加一个特殊的构造函数
record record SimpleRecord(int no, string paramStr = "New param that did not existed")
{
[Newtonsoft.Json.JsonConstructor]
public SimpleRecord(int no, string paramStr, string msg="JsonConstructor")
:this(no, paramStr)
{
if (string.IsNullOrEmpty(paramStr)) this.paramStr = "New param that did not existed";
}
}
第三个参数只是为了欺骗编译器而伪造的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.