Note that there are some explanatory texts on larger screens.

plurals
  1. POExclude property from json serialization in ApiController
    primarykey
    data
    text
    <p>I am trying to exclude properties from being serialized to JSON in web ApiControllers. I have verified the following 2 scenarios work.</p> <p>I have included the following attributes on the property I wish to exclude.</p> <pre><code>[System.Web.Script.Serialization.ScriptIgnore] [System.Xml.Serialization.XmlIgnore] </code></pre> <p>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?</p> <p><strong>UPDATE:</strong></p> <p>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.</p> <pre><code>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&lt;Person&gt; Get() { return new[] { new Person{FirstName = "John", LastName = "Doe"}, new Person{FirstName = "Jane", LastName = "Doe"} }; } } </code></pre> <p>Here is the generated output.</p> <p><strong>JSON:</strong></p> <pre><code>[ { "FirstName" : "John", "LastName" : "Doe" }, { "FirstName" : "Jane", "LastName" : "Doe" } ] </code></pre> <p><strong>XML:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;Person&gt; &lt;FirstName&gt;John&lt;/FirstName&gt; &lt;/Person&gt; &lt;Person&gt; &lt;FirstName&gt;Jane&lt;/FirstName&gt; &lt;/Person&gt; &lt;/ArrayOfPerson&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload