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 }
JSON.Net Self referencing loop detected
The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings
.
Single JsonConvert
with an overload:
JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore } );
If you'd like to make this the default behaviour, add a Global Setting with code in Application_Start()
in Global.asax.cs:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78