Files
Newtonsoft.Json/Doc/ConditionalProperties.aml
T
2012-11-03 12:54:05 +13:00

41 lines
2.5 KiB
XML

<?xml version="1.0" encoding="utf-8"?>
<topic id="ConditionalProperties" revisionNumber="1">
<developerConceptualDocument xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink">
<introduction>
<para>Json.NET has the ability to conditionally serialize properties by placing a ShouldSerialize method on a class.
This funtionality is similar to the <externalLink>
<linkText>XmlSerializer ShouldSerialize feature</linkText>
<linkUri>http://msdn.microsoft.com/en-us/library/53b8022e.aspx</linkUri>
<linkTarget>_blank</linkTarget>
</externalLink>.</para>
</introduction>
<section>
<title>ShouldSerialize</title>
<content>
<para>To conditionally serialize a property add a boolean method with the same name as the property and then prefixed the method name
with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the
property will be serialized, if it returns false and the property will be skipped.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\ConditionalPropertiesTests.cs" region="EmployeeShouldSerializeExample" title="Employee class with a ShouldSerialize method" />
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\ConditionalPropertiesTests.cs" region="ShouldSerializeClassTest" title="ShouldSerialize output" />
</content>
</section>
<section>
<title>IContractResolver</title>
<content>
<para>ShouldSerialize can also be set using an <codeEntityReference>T:Newtonsoft.Json.Serialization.IContractResolver</codeEntityReference>.
Conditionally serializing a property using an IContractResolver is useful if you don't want to place a ShouldSerialize method on a class
or you didn't declare the class and are unable to.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\ConditionalPropertiesTests.cs" region="ShouldSerializeContractResolver" title="Conditional properties with IContractResolver" />
</content>
</section>
<relatedTopics>
<codeEntityReference>T:Newtonsoft.Json.JsonSerializer</codeEntityReference>
<codeEntityReference>T:Newtonsoft.Json.Serialization.IContractResolver</codeEntityReference>
<codeEntityReference>P:Newtonsoft.Json.Serialization.JsonProperty.ShouldSerialize</codeEntityReference>
</relatedTopics>
</developerConceptualDocument>
</topic>