Search code examples
c#json-deserializationsystem.text.json

System.Text.Json: when deserializing, how can I ignore a null or empty string value for a property that has a default value set in the constructor?


I an using System.Text.Json to deserialize JSON to a model with a string-valued property TenantId that has a default value "Default Value" set in the constructor. Sometimes the JSON will contain a null or empty value for that property. How can I ignore the JSON value in that case, and leave the value set in the constructor as-is?

jsonBody

{
    "displayName": "Something",
    "id": "something",
    "ignoreCache": false,
    "tenantId": ""
}

The Model

public class Payload
{
    [JsonPropertyName("displayName")]
    public string DisplayName { get; set; }
    [JsonPropertyName("id")]
    public string Id { get; set; }
    [JsonPropertyName("ignoreCache")]
    public bool IgnoreCache { get; set; }
    [JsonPropertyName("tenantId")]
    public string TenantId { get; set; } = "Default Value"
}

Deserialization

var model = JsonSerializer.Deserialize<GroupMembersElevatedPost>(jsonBody);

Result (note: TenantId has been set to "". I want to leave it as "Default Value"):

Payload
{
    DisplayName = "Something",
    Id = "Something",
    IgnoreCache = false,
    TenantId = ""
}

Note that I have no option to change the JSON to omit the tenantId property when empty.


Solution

  • Why it should not if your json contains TenantId = ""? You need a special code that should return default string if it is "" or null, for example

        private string _tenantId;
    
        [JsonPropertyName("tenantId")]
        public string TenantId
        {
            get
            {
                return string.IsNullOrEmpty(_tenantId)
                         ? "Default Value"
                         : _tenantId;
            }
            set { _tenantId = value; }
        }