我上课了。它有几个属性可以说10.在这10个中,3个填充了剩下的7个数据是空白的.i.e。空字符串“”使用此link作为参考。我想只显示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'是User实例。我的意思是没有运气,'t'带回了所有10个属性
{"userID":"vick187","ssn":"","empID":"","schemaAgencyName":"","givenName":"","familyName":"","password":"pwd1234",...}
因此,您只能看到填充了用户ID和密码。但我有ssn,empID等仍然出现。我只想要用户ID和密码。任何帮助将不胜感激。
答案 0 :(得分:14)
仅仅装饰属性[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; }
}
答案 1 :(得分:6)
您还可以使用以下两个注释:
[DefaultValue("")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string Category { get; set; }
答案 2 :(得分:1)
我已经使用转换器完成了此操作。
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TestApp.JsonConverterResolver
{
public class IgnoreEmptyStringsConverter : JsonConverter
{
#region Methods
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var theValue = reader.Value?.ToString();
return !string.IsNullOrWhiteSpace(theValue) ? theValue : null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!string.IsNullOrWhiteSpace(value.ToString()))
{
JToken token = JToken.FromObject(value.ToString(), serializer);
token.WriteTo(writer);
return;
}
writer.WriteNull();
}
#endregion
}
}
人物模型类示例:
public class Person
{
public string Name { get; set; }
}
还有语言:
var serializerSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
Converters = new List<JsonConverter> {new IgnoreEmptyStringsConverter()}
};
var person = JsonConvert.DeserializeObject<Person>("{ \"Name\":\"\" }", serializerSettings);
var jsonPerson = JsonConvert.SerializeObject(new Person { Name = "" }, serializerSettings);
我只是从脑海里写下来。 但是我认为这就是我解决问题的方式。 也许对某人有帮助。
答案 3 :(得分:0)
尽管可接受的答案有效,但它也会删除零值的整数属性。我正在寻找更通用的东西来处理大型对象。
在这里找到了一个很好的答案:https://codearticles.ru/articles/2905?AspxAutoDetectCookieSupport=1
并将其合并为以下用例:
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType == typeof(string))
{
// Do not include emptry strings
property.ShouldSerialize = instance =>
{
return !string.IsNullOrWhiteSpace(instance.GetType().GetProperty(member.Name).GetValue(instance, null) as string);
};
}
else if (property.PropertyType == typeof(DateTime))
{
// Do not include zero DateTime
property.ShouldSerialize = instance =>
{
return Convert.ToDateTime(instance.GetType().GetProperty(member.Name).GetValue(instance, null)) != default(DateTime);
};
}
else if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
{
// Do not include zero-length lists
switch (member.MemberType)
{
case MemberTypes.Property:
property.ShouldSerialize = instance =>
{
var enumerable = instance.GetType().GetProperty(member.Name).GetValue(instance, null) as IEnumerable;
return enumerable != null ? enumerable.GetEnumerator().MoveNext() : false;
};
break;
case MemberTypes.Field:
property.ShouldSerialize = instance =>
{
var enumerable = instance.GetType().GetField(member.Name).GetValue(instance) as IEnumerable;
return enumerable != null ? enumerable.GetEnumerator().MoveNext() : false;
};
break;
}
}
return property;
}
}
可以如下使用:
JsonConvert.SerializeObject(o,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = ShouldSerializeContractResolver.Instance
});