简体   繁体   中英

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.

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";
     }
} 

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