我有课 它具有几个属性,可以说10。在这10个中,有3个填充了剩余的数据,其中7个是blank.ie空字符串“”使用此链接作为参考。我只想显示NON-NULL和NON- EMPTY字符串属性。但是最终输出具有所有10个属性。我只想看3。
namespace Mynamespace.ValueObjects { [DataContract] public class User { [DataMember(Name ="userID", IsRequired = false,EmitDefaultValue = false)] public string userID { get; set; } [DataMember(Name ="ssn", IsRequired = false,EmitDefaultValue = false)] public string ssn { get; set; } [DataMember(Name ="empID", IsRequired = false,EmitDefaultValue = false)] public string empID { get; set; } [DataMember(Name ="schemaAgencyName", IsRequired = false,EmitDefaultValue = false)] public string schemaAgencyName { get; set; } [DataMember(Name ="givenName", IsRequired = false,EmitDefaultValue = false)] public string givenName { get; set; } [DataMember(Name ="familyName", IsRequired = false,EmitDefaultValue = false)] public string familyName { get; set; } [DataMember(Name ="password", IsRequired = false,EmitDefaultValue = false)] public string password { get; set; } .... }
}
我也尝试过
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
作为属性。没运气。我也这样
var t = JsonConvert.SerializeObject(usr, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
其中“ usr”是用户实例。运气不好,我的意思是,所有10个属性都返回“ t”
{"userID":"vick187","ssn":"","empID":"","schemaAgencyName":"","givenName":"","familyName":"","password":"pwd1234",...}
如您所见,仅填充了用户ID和密码。但是我仍然显示ssn,empID等。我只想要用户名和密码。任何帮助,将不胜感激。
仅装饰属性[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]应做您想要的。除非将属性设置为空字符串。
只是想知道,为什么需要DataMemeber属性?
这是工作中的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; } }