Elad Benda Elad Benda - 1 year ago 140
C# Question

How to exclude property from Json Serialization

I have a DTO class which I Serialize


How can I exclude a public property of it?

(It has to be public, as I use it in my code somewhere else)

Answer Source

You can put a ScriptIgnore attribute on the members that shouldn't be serialized. See the example taken from here:

Consider the following (simplified) case:

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete
        get { return Id > 0 && !string.IsNullOrEmpty(Name); }

In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:

{ Id: 3, Name: 'Test User' }

PS. Don't forget to add a reference to "System.Web.Extensions" for this to work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download