Elad Benda Elad Benda - 1 month ago 16
C# Question

How to exclude property from Json Serialization

I have a DTO class which I Serialize

Json.Serialize(MyClass)


How can I exclude a public property of it?

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

Answer

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; }
    [ScriptIgnore]
    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