Is there an attribute to tell json.net to ignore all properties of a class but include all fields (regardless of access modifiers) ?
If not is there a way to create one ?
Basically I want one attribute decorating the class that will have the equivalent effect to putting [JsonIgnore]
infront of each property.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.
You can add [JsonObject(MemberSerialization.OptIn)]
attribute to your class, then everything will be ignored unless you explicitly Opt-In by using a [JsonProperty]
attribute on the members.
[JsonObject(MemberSerialization.OptIn)]
public class Address
{
[JsonProperty]
private string _field1 = "bob";
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
}
For example
using System;
using AutoFixture;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var fixture = new Fixture();
var address = fixture.Create<Address>(); // Create an address filled with junk
var json = JsonConvert.SerializeObject(address);
Console.WriteLine(json);
}
}
Will output:
{"_field1":"bob"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With