Home > Software engineering >  How to get deserialized C# record with default constructor parameter with Newton as with System.Text
How to get deserialized C# record with default constructor parameter with Newton as with System.Text

Time:07-19

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).

CodePudding user response:

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

CodePudding user response:

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

  • Related