Home > other >  how to tell JsonSerializer to ignore all properties that are of a given type?
how to tell JsonSerializer to ignore all properties that are of a given type?

Time:11-13

Basically what I want is something like below

    [SomeJsonIgnoreAnnotation]
    class MySecret {
      public int Secret { get; set; } = 1;
    }

    class A {
      public MySecret SecretA { get; set; } = new();
    }

    class B {
      public MySecret SecretB { get; set; } = new();
    }

And System.Text.Json.JsonSerializer would treat class A and class B as if SecretA and SecretB are annotated with [JsonIgnore]

CodePudding user response:

The simple solution:

class MySecret {
    [JsonIgnore]
    public int Secret { get; set; } = 1;
}

Now the property Secret will never be serialized by any class using the class MySecret.

CodePudding user response:

if you have many properties it is more effective to use DataContract attribute instead of JsonIgnore

   [DataContract]
    public class MySecret
    {
        public int Secret { get; set; } = 1;

    }

test

    var a = new A();
    JsonConvert.SerializeObject(a); // {"SecretA":{}}

if you still want to serialize some members you can add DataMember attribute

[System.Runtime.Serialization.DataContract]
public class MySecret
{
    public int Secret { get; set; } = 1;

    [DataMember]
    public int SecretShow { get; set; } = 2;
}

test

{"SecretA":{"SecretShow":2}}
  • Related