Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude property from json serialization in ApiController

I am trying to exclude properties from being serialized to JSON in web ApiControllers. I have verified the following 2 scenarios work.

I have included the following attributes on the property I wish to exclude.

[System.Web.Script.Serialization.ScriptIgnore]
[System.Xml.Serialization.XmlIgnore]

If I manually serialize my object using the JavaScriptSerializer, the property is excluded. Also, if I view the serialized XML output from the web ApiController, the property is excluded. The problem is, the serialized JSON via the web ApiController still contains the property. Is there another attribute that I can use that will exclude the property from JSON serialization?

UPDATE:

I realized all my tests were in a much more complex project and that I hadn't tried this in a an isolated environment. I did this and am still getting the same results. Here is an example of some code that is failing.

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>
like image 219
Adam Carr Avatar asked Dec 13 '22 02:12

Adam Carr


1 Answers

Be aware that JSON serialization is changing in Web API.

In the beta release, Web API used DataContractJsonSerializer to serialize JSON. However, this has changed; the latest version of Web API uses json.net by default, although you can override this and use DataContractJsonSerializer instead.

With DataContractJsonSerializer, you can use [DataContract] attributes to control the serialization. I'm stil not very familiar with json.net, so I don't know how it controls serialization.

like image 103
Mike Wasson Avatar answered May 14 '23 02:05

Mike Wasson