I am trying to exclude properties from serialization in JSON in web ApiControllers. I checked the following 2 work scenarios.
I have included the following attributes in the property that I want to exclude.
[System.Web.Script.Serialization.ScriptIgnore] [System.Xml.Serialization.XmlIgnore]
If I manually serialize my object using JavaScriptSerializer, the property is excluded. Also, if I look at the serialized XML output from the ApiController web, the property is excluded. The problem is that serialized JSON through the ApiController web interface still contains the property. Is there any other attribute that I can use that will exclude the property from JSON serialization?
UPDATE:
I realized that all my tests were in a much more complex project and that I did not try this in an isolated environment. I did this and still get the same results. Here is an example of some code that fails.
public class Person { public string FirstName { get; set; } [System.Web.Script.Serialization.ScriptIgnore] [System.Xml.Serialization.XmlIgnore] public string LastName { get; set; } } public class PeopleController : ApiController { public IEnumerable<Person> Get() { return new[] { new Person{FirstName = "John", LastName = "Doe"}, new Person{FirstName = "Jane", LastName = "Doe"} }; } }
Here is the generated output.
JSON:
[ { "FirstName" : "John", "LastName" : "Doe" }, { "FirstName" : "Jane", "LastName" : "Doe" } ]
XML:
<?xml version="1.0" encoding="utf-8"?> <ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Person> <FirstName>John</FirstName> </Person> <Person> <FirstName>Jane</FirstName> </Person> </ArrayOfPerson>
source share