Is there something like the opposite of a JsonIgnore?

前端 未结 2 657
心在旅途
心在旅途 2021-01-13 16:51

The JsonIgnore attribute can be used to ignore certain properties in serialization. I was wondering if it is possible to do the opposite of that? So a JsonSeria

相关标签:
2条回答
  • 2021-01-13 17:44

    Yes there is. When you mark your class with [JsonObjectAttribute] and pass the MemberSerialization.OptIn parameter, member serialization is opt-in. Then mark your members with [JsonProperty] to include them for serialization.

    [JsonObject(MemberSerialization.OptIn)]
    public class Person
    {
        [JsonProperty]
        public string Name { get; set; }
    
        // not serialized because mode is opt-in
        public string Department { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-13 17:47

    An alternative to MemberSerialization.OptIn is using DataContract/DataMember attributes:

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

    Source: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

    0 讨论(0)
提交回复
热议问题