Home > Software engineering >  JsonConvert PopulateObject when updating object doesnt populate null value to nullable integer
JsonConvert PopulateObject when updating object doesnt populate null value to nullable integer

Time:12-26

I am trying to update an user object

Here is my model:

public class User:BaseModel
{
    [Display(Name="E-Posta"),Required(ErrorMessage ="Kullanıcı adı (Email) Zorunludur")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "Email")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress(ErrorMessage = "Hatalı E-Posta")]
    public string Email { get; set; }
    [Display(Name="Firma Ünvanı")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "FirmTitle")]
    public string FirmTitle { get; set; }
    [Display(Name = "Vergi Numarası")]
    [StringLength(11, ErrorMessage = "Vergi Kimlik Numarası 10 veya 11 karakter olmalıdır", MinimumLength = 10)]
    [JsonProperty(PropertyName = "VKN")]
    public string VKN { get; set; }
    [Display(Name="Alıcılar E-Posta")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "DocumentReceivers")]
    public string DocumentReceivers { get; set; }
    [Display(Name="Sap Lojistik Id")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "SAPLogisticId")]
    public int? SAPLogisticId { get; set; }
    [Display(Name="Parola"), Required(ErrorMessage = "Parola Zorunludur")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "Password")]
    [DataType(DataType.Password)]
    public string Password { get; set; }
    [Display(Name="Rol"),Required(ErrorMessage ="Bu alan Gereklidir")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "Role")]
    public string Role { get; set; }
    [Display(Name="Oluşturulma Tarihi")]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "CreatedDate")]
    public DateTime CreatedDate { get; set; }
}

I have one nullable int? named SAPLogisticId which I am trying to set null value

var values = "{\"SAPLogisticId\":null}";
int key=4;
var user = userManager.Get(key);
JsonConvert.PopulateObject(values, user,new JsonSerializerSettings()
{
   NullValueHandling = NullValueHandling.Ignore,
   ContractResolver = new CamelCasePropertyNamesContractResolver() { NamingStrategy = null }
});

But it is not setting the value of SAPLogisticId it does nothing

Other properties does WORK

CodePudding user response:

It's because you're using NullValueHandling = NullValueHandling.Ignore. You're telling the serializer to ignore null values. If you remove it from both the JsonProperty attribute for SAPLogisticId and the JsonSerializerSettings it will work as expected.

  • Related