简体   繁体   中英

How to get deserialized C# record with default constructor parameter with Newton as with System.Text.Json?

Let's say at first I have a record with only one parameter "int no". Later, as the program evolves, new param with a default value is added resulting:

record SimpleRecord(int no, string paramStr = "New param that did not existed");

now parsing previously saved json with two different libs:

 string jsonText = "{\"no\":10}";
 SimpleRecord? parsedJson1 = System.Text.Json.JsonSerializer.Deserialize<SimpleRecord>(jsonText);
 SimpleRecord? parsedJson2 = Newtonsoft.Json.JsonConvert.DeserializeObject<SimpleRecord>(jsonText);

I would expect parsed record as System.Text.Json -> {SimpleRecord { no = 10, paramStr = New param that did not existed }} Newton parsed record is {SimpleRecord { no = 10, paramStr = }}

paramStr is null. How to achieve the same result as System.Text.Json with Newton library? (I have existing project with Newton so trying to avoid rewriting).

So there's a few ways to approach it, first you can add a [DefaultValue(" ")] attribute to you're parameter (for more info see documentation ). ex:

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

Second option would be to define a default value in you're class like this (if you are using c# 6 or above). ex:

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

For more examples you could look at this answer

I prefer to add a special constructor for 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";
    }
}

the third parameter is just a fake to cheat a compiller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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