如何从 Json 序列化中排除属性 [英] How to exclude property from Json Serialization
本文介绍了如何从 Json 序列化中排除属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个序列化的 DTO 类
I have a DTO class which I Serialize
Json.Serialize(MyClass)
如何排除它的公共属性?
(它必须是公开的,因为我在其他地方的代码中使用它)
(It has to be public, as I use it in my code somewhere else)
推荐答案
如果您使用的是 Json.Net 属性 [JsonIgnore]
将简单地忽略字段/属性,而序列化或反序列化.
If you are using Json.Net attribute [JsonIgnore]
will simply ignore the field/property while serializing or deserialising.
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
或者您可以使用 DataContract 和 DataMember 属性来选择性地序列化/反序列化属性/字段.
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
这篇关于如何从 Json 序列化中排除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文