Serialize only interface properties to JSON with Json.net

前端 未结 9 1952
孤街浪徒
孤街浪徒 2020-12-08 19:50

With a simple class/interface like this

public interface IThing
{
    string Name { get; set; }
}

public class Thing : IThing
{
    public int Id { get; se         


        
9条回答
  •  北海茫月
    2020-12-08 20:13

    An alternative to [JsonIgnore] are the [DataContract] and [DataMember] attributes. If you class is tagged with [DataContract] the serializer will only process properties tagged with the [DataMember] attribute (JsonIgnore is an "opt-out" model while DataContract is "op-in").

    [DataContract]
    public class Thing : IThing
    {
        [DataMember]
        public int Id { get; set; }
    
        public string Name { get; set; }
    }
    

    The limitation of both approaches is that they must be implemented in the class, you cannot add them to the interface definition.

提交回复
热议问题