繁体   English   中英

如何使用 Newton 和 System.Text.Json 一样使用默认构造函数参数获取反序列化的 C# 记录?

[英]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 相同的结果? (我有牛顿的现有项目,所以试图避免重写)。

所以有几种方法可以解决它,首先你可以为你的参数添加一个[DefaultValue(" ")]属性(有关更多信息,请参阅文档)。 前任:

[DefaultValue(" ")]
public string FullName
{
    get { return FirstName + " " + LastName; }
}

第二个选项是在你的类中定义一个默认值(如果你使用的是 c# 6 或更高版本)。 前任:

public string c { get; set; } = "foo";

有关更多示例,您可以查看此答案

我更喜欢为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM