Json ignore on class level

Exclude all instances of a class from serialization in Newtonsoft.Json

Every custom type can opt how it will be serialized.

To example, mark the type with [JsonObject(MemberSerialization = MemberSerialization.OptIn)] and then you have to mark something with [JsonProperty] otherwise nothing will be serialized. So even if property of custom type is serializable the type may produce nothing ({}) to serialize:

public class A
{
    public string Test { get; set; } = "Test";
    public B B { get; set; } = new B();
}

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class B
{
    public string Foo { get; set; } = "Foo";
}

and then

Console.WriteLine(JsonConvert.SerializeObject(new A()));

will produce

{"Test":"Test","B":{}}"

With this approach you will have problems to serialize B at all. Which is not very bright idea, don't you think?

 

MemberSerialization枚举类型的官方解释Specifies the member serialization options for the Newtonsoft.Json.JsonSerializer.

public enum MemberSerialization
{
//
// Summary:
// All public members are serialized by default. Members can be excluded using Newtonsoft.Json.JsonIgnoreAttribute
// or System.NonSerializedAttribute. This is the default member serialization mode.
OptOut = 0,
//
// Summary:
// Only members marked with Newtonsoft.Json.JsonPropertyAttribute or System.Runtime.Serialization.DataMemberAttribute
// are serialized. This member serialization mode can also be set by marking the
// class with System.Runtime.Serialization.DataContractAttribute.
OptIn = 1,
//
// Summary:
// All public and private fields are serialized. Members can be excluded using Newtonsoft.Json.JsonIgnoreAttribute
// or System.NonSerializedAttribute. This member serialization mode can also be
// set by marking the class with System.SerializableAttribute and setting IgnoreSerializableAttribute
// on Newtonsoft.Json.Serialization.DefaultContractResolver to false.
Fields = 2
}

 

上一篇:VSTO 添加引用和第三方类库


下一篇:Newtonsoft 六个超简单又实用的特性,值得一试 【上篇】