如何在 servicestack json 序列化程序中省略仅获取属性? [英] How to omit Get only properties in servicestack json serializer?
问题描述
我有一个对象,我正在使用 ServiceStack.Text 命名空间中的 ToJson<>()
方法对其进行反序列化.
I have an object which I am de-serializing using ToJson<>()
method from ServiceStack.Text namespace.
如何在序列化过程中省略所有 GET
属性?有没有像 [Ignore]
这样的属性或者我可以用来装饰我的属性的东西,这样它们就可以被省略?
How to omit all the GET
only propeties during serialization? Is there any attribute like [Ignore]
or something that I can decorate my properties with, so that they can be omitted?
谢谢
推荐答案
ServiceStack 的文本序列化器如下.NET 的 DataContract 序列化程序行为,这意味着您可以通过使用选择退出 [IgnoreDataMember]
属性
ServiceStack's Text serializers follows .NET's DataContract serializer behavior, which means you can ignore data members by using the opt-out [IgnoreDataMember]
attribute
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
[IgnoreDataMember]
public string IsIgnored { get; set; }
}
一个选择加入的替代方法是用[DataMember]
装饰您想要序列化的每个属性.其余属性未序列化,例如:
An opt-in alternative is to decorate every property you want serialized with [DataMember]
. The remaining properties aren't serialized, e.g:
[DataContract]
public class Poco
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
public string IsIgnored { get; set; }
}
最后还有一个不需要属性的非侵入式选项,例如:
Finally there's also a non-intrusive option that doesn't require attributes, e.g:
JsConfig<Poco>.ExcludePropertyNames = new [] { "IsIgnored" };
动态指定应该序列化的属性
ServiceStack 的 Serializers 还支持动态控制序列化,通过提供传统命名的 ShouldSerialize({PropertyName})
方法来指示属性是否应该被序列化,例如:
Dynamically specifying properties that should be serialized
ServiceStack's Serializers also supports dynamically controlling serialization by providing conventionally named ShouldSerialize({PropertyName})
methods to indicate whether a property should be serialized or not, e.g:
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
public string IsIgnored { get; set; }
public bool? ShouldSerialize(string fieldName)
{
return fieldName == "IsIgnored";
}
}
更多示例在 ConditionalSerializationTests.cs
这篇关于如何在 servicestack json 序列化程序中省略仅获取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!