Remove empty string properties from json serialized object

前端 未结 4 1130
暖寄归人
暖寄归人 2020-12-15 23:06

I have a class. It has several properties lets say 10. Out of these 10, 3 are filled with data remaining 7 are blank.i.e. empty strings \"\" Used this link as reference. I w

4条回答
  •  猫巷女王i
    2020-12-15 23:22

    Just decorating the properties [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] ONLY should do what you want. Unless the property is getting set to an empty string.

    Just wondering, why do you need the DataMemeber attribute?

    Here is a link to a working dotnetfiddle

    using System;
    using Newtonsoft.Json;
    using System.ComponentModel;
    
    public class Program
    {
    
        public static void Main()
        {
            var user = new User();
    
            user.UserID = "1234";
            user.ssn = "";
    
            var settings = new JsonSerializerSettings();
    
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.DefaultValueHandling = DefaultValueHandling.Ignore;
    
    
            Console.WriteLine(JsonConvert.SerializeObject(user, settings));
        }
    }
    
    public class User
    {
        [DefaultValue("")]
        public string UserID { get; set; }
    
        [DefaultValue("")]
        public string ssn { get; set; }
    
        [DefaultValue("")]
        public string empID { get; set; }
    
        [DefaultValue("")]
        public string schemaAgencyName { get; set; }
    
        [DefaultValue("")]
        public string givenName { get; set; }
    
        [DefaultValue("")]
        public string familyName { get; set; }
    
        [DefaultValue("")]
        public string password { get; set; }
    }
    

提交回复
热议问题