Home > other >  System.Text.Json: when deserializing, how can I ignore a null or empty string value for a property t
System.Text.Json: when deserializing, how can I ignore a null or empty string value for a property t

Time:08-09

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.

CodePudding user response:

Why it should not if your json contains TenantId = ""? You need a special code that should assign default value if it is "", for example

private string _tenantId = "Default Value";

[JsonPropertyName("tenantId")]
public string TenantId { 
get { return _tenantId; } 
set { if (!string.IsNullOrEmpty(value))  _tenantId=value;
      else _tenantId = "Default Value";
     }
} 
  • Related