-Documentation

This commit is contained in:
James Newton-King
2012-10-31 13:24:47 +13:00
parent 6365a9f555
commit d92b8ceeb5
11 changed files with 413 additions and 169 deletions
+3
View File
@@ -5,3 +5,6 @@ TestResults/
AppPackages/ AppPackages/
*.suo *.suo
*.user *.user
_ReSharper.*
*.ReSharper.user
*.resharper.user
+41
View File
@@ -0,0 +1,41 @@
<?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>M:Newtonsoft.Json.Serialization.JsonProperty.ShouldSerialize</codeEntityReference>
</relatedTopics>
</developerConceptualDocument>
</topic>
+17
View File
@@ -45,6 +45,23 @@
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ContractResolver" title="ContractResolver" /> <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ContractResolver" title="ContractResolver" />
</content> </content>
</section> </section>
<section>
<title>Custom Examples</title>
<content>
<para>Setting a <codeEntityReference>T:Newtonsoft.Json.JsonConverter</codeEntityReference> on a type
using an IContractResolver.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\PerformanceTests.cs" region="JsonConverterContractResolver" title="Use JsonConverter with IContractResolver" />
<para><externalLink>
<linkText>Conditionally serializing properties</linkText>
<linkUri>ConditionalProperties.htm</linkUri>
<linkTarget>_self</linkTarget>
</externalLink> using an IContractResolver.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\ConditionalPropertiesTests.cs" region="ShouldSerializeContractResolver" title="Conditional properties with IContractResolver" />
</content>
</section>
<relatedTopics> <relatedTopics>
<codeEntityReference>T:Newtonsoft.Json.Serialization.IContractResolver</codeEntityReference> <codeEntityReference>T:Newtonsoft.Json.Serialization.IContractResolver</codeEntityReference>
<codeEntityReference>T:Newtonsoft.Json.Serialization.DefaultContractResolver</codeEntityReference> <codeEntityReference>T:Newtonsoft.Json.Serialization.DefaultContractResolver</codeEntityReference>
+3 -3
View File
@@ -36,7 +36,7 @@
<content> <content>
<para>Passing a <codeEntityReference>T:Newtonsoft.Json.JsonConverter</codeEntityReference> to SerializeObject or DeserializeObject provides a simple way to completely <para>Passing a <codeEntityReference>T:Newtonsoft.Json.JsonConverter</codeEntityReference> to SerializeObject or DeserializeObject provides a simple way to completely
change how an object is serialized. There is however a small overhead; the CanConvert method is called for every change how an object is serialized. There is however a small overhead; the CanConvert method is called for every
type to check whether serialization should be handled by that JsonConverter.</para> value to check whether serialization should be handled by that JsonConverter.</para>
<para>There are a couple of ways to continue to use JsonConverters without any overhead. The simplest way <para>There are a couple of ways to continue to use JsonConverters without any overhead. The simplest way
is to specify the JsonConverter using the <codeEntityReference>T:Newtonsoft.Json.JsonConverterAttribute</codeEntityReference>. This attribute tells the serializer is to specify the JsonConverter using the <codeEntityReference>T:Newtonsoft.Json.JsonConverterAttribute</codeEntityReference>. This attribute tells the serializer
to always use that converter when serializing and deserializing the type, without the check.</para> to always use that converter when serializing and deserializing the type, without the check.</para>
@@ -54,8 +54,8 @@
<section> <section>
<title>Manually Serialize</title> <title>Manually Serialize</title>
<content> <content>
<para>The absolute fastest way to read and write JSON is to use JsonTextReader and JsonTextWriter directly. Using a reader or writer <para>The absolute fastest way to read and write JSON is to use JsonTextReader/JsonTextWriter directly to manually serialize types.
directly skips any of the overhead from a serializer such as reflection.</para> Using a reader or writer directly skips any of the overhead from a serializer such as reflection.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\PerformanceTests.cs" region="ReaderWriter" title="Manually serialize using JsonTextWriter" /> <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\PerformanceTests.cs" region="ReaderWriter" title="Manually serialize using JsonTextWriter" />
+4 -3
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Topics> <Topics>
<Topic id="Introduction" visible="True" isDefault="true" /> <Topic id="Introduction" visible="True" isDefault="true" />
<Topic id="SerializingJSON" visible="True" title="Serializing and Deserializing JSON"> <Topic id="SerializingJSON" visible="True" isExpanded="true" title="Serializing and Deserializing JSON">
<Topic id="SerializationSettings" visible="True" title="Serialization Settings" /> <Topic id="SerializationSettings" visible="True" title="Serialization Settings" />
<Topic id="SerializationGuide" visible="True" title="Serialization Guide" /> <Topic id="SerializationGuide" visible="True" title="Serialization Guide" />
<Topic id="SerializationAttributes" visible="True" title="Serialization Attributes" /> <Topic id="SerializationAttributes" visible="True" title="Serialization Attributes" />
@@ -9,11 +9,12 @@
<Topic id="SerializationErrorHandling" visible="True" title="Serialization Error Handling" /> <Topic id="SerializationErrorHandling" visible="True" title="Serialization Error Handling" />
<Topic id="PreserveObjectReferences" visible="True" title="Preserving Object References" /> <Topic id="PreserveObjectReferences" visible="True" title="Preserving Object References" />
<Topic id="CustomCreationConverter" visible="True" /> <Topic id="CustomCreationConverter" visible="True" />
<Topic id="ContractResolver" visible="True" />
<Topic id="SerializingCollections" visible="True" title="Serializing Collections" /> <Topic id="SerializingCollections" visible="True" title="Serializing Collections" />
<Topic id="DatesInJSON" visible="True" title="Serializing Dates in JSON" /> <Topic id="DatesInJSON" visible="True" title="Serializing Dates in JSON" />
<Topic id="ReducingSerializedJSONSize" visible="True" title="Reducing Serialized JSON Size" /> <Topic id="ReducingSerializedJSONSize" visible="True" title="Reducing Serialized JSON Size" />
<Topic id="SerializingJSONFragments" visible="True" title="Serializing Partial JSON Fragments" /> <Topic id="SerializingJSONFragments" visible="True" title="Serializing Partial JSON Fragments" />
<Topic id="ConditionalProperties" visible="True" title="Conditional Properties" />
<Topic id="ContractResolver" visible="True" isSelected="true" title="Serialization using ContractResolver" />
</Topic> </Topic>
<Topic id="LINQtoJSON" visible="True" title="LINQ to JSON"> <Topic id="LINQtoJSON" visible="True" title="LINQ to JSON">
<Topic id="ParsingLINQtoJSON" visible="True" title="Parsing JSON" /> <Topic id="ParsingLINQtoJSON" visible="True" title="Parsing JSON" />
@@ -21,7 +22,7 @@
<Topic id="QueryingLINQtoJSON" visible="True" title="Querying JSON with LINQ" /> <Topic id="QueryingLINQtoJSON" visible="True" title="Querying JSON with LINQ" />
<Topic id="SelectToken" visible="True" title="Querying JSON with SelectToken" /> <Topic id="SelectToken" visible="True" title="Querying JSON with SelectToken" />
</Topic> </Topic>
<Topic id="Performance" visible="True" isSelected="true" title="Performance" /> <Topic id="Performance" visible="True" title="Performance" />
<Topic id="JsonSchema" visible="True" title="Validating JSON" /> <Topic id="JsonSchema" visible="True" title="Validating JSON" />
<Topic id="ReadingWritingJSON" visible="True" title="Basic Reading and Writing JSON" /> <Topic id="ReadingWritingJSON" visible="True" title="Basic Reading and Writing JSON" />
<Topic id="ConvertingJSONandXML" visible="True" title="Converting between JSON and XML" /> <Topic id="ConvertingJSONandXML" visible="True" title="Converting between JSON and XML" />
+3 -2
View File
@@ -8,7 +8,7 @@
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{fd19f68e-72c8-4576-9775-b4480b0db686}</ProjectGuid> <ProjectGuid>{fd19f68e-72c8-4576-9775-b4480b0db686}</ProjectGuid>
<SHFBSchemaVersion>1.9.3.0</SHFBSchemaVersion> <SHFBSchemaVersion>1.9.5.0</SHFBSchemaVersion>
<!-- AssemblyName, Name, and RootNamespace are not used by SHFB but Visual <!-- AssemblyName, Name, and RootNamespace are not used by SHFB but Visual
Studio adds them anyway --> Studio adds them anyway -->
<AssemblyName>Documentation</AssemblyName> <AssemblyName>Documentation</AssemblyName>
@@ -32,7 +32,7 @@
<BuildLogFile> <BuildLogFile>
</BuildLogFile> </BuildLogFile>
<HelpFileFormat>Website</HelpFileFormat> <HelpFileFormat>Website</HelpFileFormat>
<FrameworkVersion>.NET 4.0.30319</FrameworkVersion> <FrameworkVersion>.NET Framework 4.0</FrameworkVersion>
<HelpTitle>Json.NET - Documentation</HelpTitle> <HelpTitle>Json.NET - Documentation</HelpTitle>
<PresentationStyle>vs2005</PresentationStyle> <PresentationStyle>vs2005</PresentationStyle>
<NamingMethod>MemberName</NamingMethod> <NamingMethod>MemberName</NamingMethod>
@@ -137,6 +137,7 @@
<Content Include="donate.gif" /> <Content Include="donate.gif" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="ConditionalProperties.aml" />
<None Include="CustomCreationConverter.aml" /> <None Include="CustomCreationConverter.aml" />
<None Include="ContractResolver.aml" /> <None Include="ContractResolver.aml" />
<None Include="ConvertingJSONandXML.aml" /> <None Include="ConvertingJSONandXML.aml" />
@@ -0,0 +1,177 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET35 || NET20 || PORTABLE)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Documentation
{
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
}
#region ShouldSerializeContractResolver
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(Employee) && property.PropertyName == "Manager")
{
property.ShouldSerialize =
instance =>
{
Employee e = (Employee) instance;
return e.Manager != e;
};
}
return property;
}
}
#endregion
[TestFixture]
public class ConditionalPropertiesTests : TestFixtureBase
{
#region EmployeeShouldSerializeExample
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
#endregion
[Test]
public void ShouldSerializeClassTest()
{
#region ShouldSerializeClassTest
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
// mike is his own manager
// ShouldSerialize will skip this property
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
#endregion
Assert.AreEqual(@"[
{
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
},
{
""Name"": ""Mike Manager""
}
]", json);
}
[Test]
public void ShouldSerializeContractResolverTest()
{
Newtonsoft.Json.Tests.Documentation.Employee joe = new Newtonsoft.Json.Tests.Documentation.Employee();
joe.Name = "Joe Employee";
Newtonsoft.Json.Tests.Documentation.Employee mike = new Newtonsoft.Json.Tests.Documentation.Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
mike.Manager = mike;
string json = JsonConvert.SerializeObject(
new[] {joe, mike},
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = ShouldSerializeContractResolver.Instance
});
Assert.AreEqual(@"[
{
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
},
{
""Name"": ""Mike Manager""
}
]", json);
}
}
}
#endif
@@ -80,10 +80,13 @@ namespace Newtonsoft.Json.Tests.Documentation
#region JsonConverterContractResolver #region JsonConverterContractResolver
public class ConverterContractResolver : DefaultContractResolver public class ConverterContractResolver : DefaultContractResolver
{ {
public new static readonly ConverterContractResolver Instance = new ConverterContractResolver();
protected override JsonContract CreateContract(Type objectType) protected override JsonContract CreateContract(Type objectType)
{ {
JsonContract contract = base.CreateContract(objectType); JsonContract contract = base.CreateContract(objectType);
// this will only be called once and then cached
if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset)) if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset))
contract.Converter = new JavaScriptDateTimeConverter(); contract.Converter = new JavaScriptDateTimeConverter();
@@ -117,7 +120,7 @@ namespace Newtonsoft.Json.Tests.Documentation
{ {
string json = JsonConvert.SerializeObject(new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc), new JsonSerializerSettings string json = JsonConvert.SerializeObject(new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc), new JsonSerializerSettings
{ {
ContractResolver = new ConverterContractResolver() ContractResolver = ConverterContractResolver.Instance
}); });
Console.WriteLine(json); Console.WriteLine(json);
@@ -117,6 +117,7 @@
<Compile Include="Converters\StringEnumConverterTests.cs" /> <Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Converters\VersionConverterTests.cs" /> <Compile Include="Converters\VersionConverterTests.cs" />
<Compile Include="Documentation\ConvertingJsonAndXmlTests.cs" /> <Compile Include="Documentation\ConvertingJsonAndXmlTests.cs" />
<Compile Include="Documentation\ConditionalPropertiesTests.cs" />
<Compile Include="Documentation\PerformanceTests.cs" /> <Compile Include="Documentation\PerformanceTests.cs" />
<Compile Include="Documentation\JsonSchemaTests.cs" /> <Compile Include="Documentation\JsonSchemaTests.cs" />
<Compile Include="Documentation\ReadingAndWritingJsonTests.cs" /> <Compile Include="Documentation\ReadingAndWritingJsonTests.cs" />
@@ -76,5 +76,5 @@ using System.Security;
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC #if !PocketPC
[assembly: AssemblyFileVersion("4.5.10.15427")] [assembly: AssemblyFileVersion("4.5.10.15431")]
#endif #endif
@@ -90,7 +90,7 @@ using System.Security;
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC #if !PocketPC
[assembly: AssemblyFileVersion("4.5.10.15427")] [assembly: AssemblyFileVersion("4.5.10.15431")]
#endif #endif
[assembly: CLSCompliant(true)] [assembly: CLSCompliant(true)]