【问题标题】:Is there something like the opposite of a JsonIgnore?有没有类似 JsonIgnore 的反义词?
【发布时间】:2017-04-27 07:00:50
【问题描述】:

JsonIgnore 属性可用于忽略序列化中的某些属性。我想知道是否可以做相反的事情?所以 JsonSerializer 会忽略每个属性,除非它上面有特殊属性?

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    是的,有。当你用[JsonObjectAttribute] 标记你的类并传递MemberSerialization.OptIn 参数时,成员serialization is opt-in。然后用[JsonProperty] 标记您的成员,以将它们包含在序列化中。

    [JsonObject(MemberSerialization.OptIn)]
    public class Person
    {
        [JsonProperty]
        public string Name { get; set; }
    
        // not serialized because mode is opt-in
        public string Department { get; set; }
    }
    

    【讨论】:

    • 或者,可以使用data contract attributes 达到同样的效果。
    • @dbc 我确实喜欢 Json 属性的替代品。我选择了 Json 属性,因为它们允许将来轻松地进行进一步的自定义,并且它们需要付出同样的努力来应用。数据契约属性的优点是大多数用户已经熟悉它们。
    【解决方案2】:

    MemberSerialization.OptIn 的替代方法是使用 DataContract/DataMember 属性:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      相关资源
      最近更新 更多