How to exclude property from Json Serialization

后端 未结 7 1544
粉色の甜心
粉色の甜心 2020-11-22 13:22

I have a DTO class which I Serialize

Json.Serialize(MyClass)

How can I exclude a public property of it?

(It has to

7条回答
  •  萌比男神i
    2020-11-22 13:31

    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 Features { get; set; }
    
      // ignored
      [JsonIgnore]
      public DateTime LastModified { get; set; }
    }
    

    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; }
    }
    

    Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details

提交回复
热议问题