Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net attribute to ignore all properties

Tags:

c#

json.net

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.

like image 582
kofifus Avatar asked Jul 02 '18 22:07

kofifus


People also ask

How do I ignore properties in JSON?

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.

What is Jsonproperty attribute?

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.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

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"}
like image 77
Kevin Smith Avatar answered Sep 20 '22 13:09

Kevin Smith