Newtonsoft ignore attributes?

According to Json.NET documentation

You can add method to your class: public bool ShouldSerialize_________(){...} and fill in the blank with the name of the property you don't want to serialize. If the method returns false, the property will be ignored.

The example from the documentation doesn't want to serialize an employee's manager if the manager is the same employee.

public class Employee
{
    public string Name { get; set; }
    public Employee Manager { get; set; }

    public bool ShouldSerializeManager()
    {
        // don't serialize the Manager property if an employee is their own manager
        return (Manager != this);
    }
}

You could put some kind of inhibit setting on your class:

public class DTO
{
    [JsonIgnore]
    public bool IsWritingToDatabase { get; set; }
    public string AlwaysSerialize { get; set; }
    public string Optional { get; set; }

    public bool ShouldSerializeOptional()
    {
        return IsWritingToDatabase;
    }
}

But, this isn't much simpler than having two objects. So I would recommend doing as @zbugs says, and having separate definitions for API-side and DB-side.


I'm not sure if this is what you're after, but from what I understand you're looking for the [JsonIgnore] attribute. Stops properties from being serialized with the rest of the object into to JSON.

[JsonIgnore]
public string Whatever{ get; set; }

One suggestion that you may not like. For best practices, I recommend having two almost identical objects. One specifically for your Data Access Layer (Domain Object) which maps to your DB. And a separate DTO that your apps care about. This way the Domain Object will mostly contain more properties than the DTO and you can separate the concerns.