-Updated documentation

-Added complete ADO.NET Entities serialization and deserialization
This commit is contained in:
JamesNK
2009-07-26 06:34:28 +00:00
parent 265abaf08c
commit b20d58bb92
26 changed files with 1491 additions and 409 deletions
+8 -4
View File
@@ -50,8 +50,8 @@
</div>
</div></div>
<p>In most cases this is the desired result but in certain scenarios writing the second item in the list as a reference to the first is a better solution.
If the above JSON was deserialized now then returned list would contain two
completely seperate Person objects with the same values. Writing references by value will also cause problems on objects where a
If the above JSON was deserialized now then the returned list would contain two
completely separate Person objects with the same values. Writing references by value will also cause problems on objects where a
circular reference occurs.</p>
<h3>PreserveReferencesHandling</h3>
@@ -93,14 +93,18 @@
</div>
</div></div>
<p>Now only one Person object is created and the deserialized list contains two references to it, mirroring what serialized.</p>
<p>The first Person in the list is serizlied with the addition of an object Id. The
second Person in JSON is now only a reference to the first.</p>
<p>With PreserveReferencesHandling on now only one Person object is created on
deserialization and the list contains two references to it, mirroring what we
started with.</p>
<h3>IsReference on JsonObjectAttribute, JsonArrayAttribute and JsonPropertyAttribute</h3>
<p>The PreserveReferencesHandling setting on the JsonSerializer will change
how all objects are serialized and deserialized. For fine grain control over which
objects and members should be serialized there is the IsReference property on
objects and members should be serialized as a reference there is the IsReference property on
the JsonObjectAttribute, JsonArrayAttribute and JsonPropertyAttribute.</p>
<p>Setting IsReference on JsonObjectAttribute or JsonArrayAttribute to true will
mean the JsonSerializer will always serialize the type the attribute is against
+118
View File
@@ -0,0 +1,118 @@
<html>
<head>
<title>Customizing JSON serialization with attributes</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<link href="custom.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="control">
<span class="productTitle">Json.NET - Quick Starts & API Documentation</span><br />
<span class="topicTitle">Customizing JSON serialization with attributes</span></div>
<div id="content">
<span style="color: DarkGray"> </span>
<p>Attributes can be used to control how Json.NET serializes and deserializes .NET objects.</p>
<ul>
<li><a href="./html/T_Newtonsoft_Json_JsonObjectAttribute.htm">JsonObjectAttribute</a> - Placed on classes to control how it should be serialized as a JSON object.</li>
<li><a href="./html/T_Newtonsoft_Json_JsonArrayAttribute.htm">JsonArrayAttribute</a> - Placed on collections to control how it should be serialized as a JSON array.</li>
<li><a href="./html/T_Newtonsoft_Json_JsonPropertyAttribute.htm">JsonPropertyAttribute</a> - Placed on fields and properties to control how it should be serialized as a property in a JSON object.</li>
<li><a href="./html/T_Newtonsoft_Json_JsonConverterAttribute.htm">JsonConverterAttribute</a> - Placed on either classes or fields and properties to specify which JsonConverter should be used during serialization.</li>
</ul>
<p>As well as using the built-in Json.NET attributes, Json.NET also looks for the
<a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> and
<a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataMember</a> attributes when determining how JSON is to be serialized and deserialized. If both are present the Json.NET serialization attributes take precedence.</p>
<div class="overflowpanel"> <div class="code">
<div style="font-family: Courier New; font-size: 10pt; color: black;">
<pre style="margin: 0px;">[<span style="color: #2b91af;">JsonObject</span>(<span style="color: #2b91af;">MemberSerialization</span>.OptIn)]</pre>
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Person</span></pre>
<pre style="margin: 0px;">{</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// "John Smith"</span></pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonProperty</span>]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">string</span> Name { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// "2000-12-15T22:11:03"</span></pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonProperty</span>]</pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonConverter</span>(<span style="color: blue;">typeof</span>(<span style="color: #2b91af;">IsoDateTimeConverter</span>))]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> BirthDate { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// new Date(976918263055)</span></pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonProperty</span>]</pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonConverter</span>(<span style="color: blue;">typeof</span>(<span style="color: #2b91af;">JavaScriptDateTimeConverter</span>))]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> LastModified { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// not serialized</span></pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">string</span> Department { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
</div></div>
<h5>JsonObjectAttribute</h5>
<p>The MemberSerialization flag on this attribute specifies whether member serialization is opt-in (a member must have the JsonProperty or DataMember attribute to be serialized) or opt-out (everything is serialized by default but can be ignored with the JsonIgnoreAttribute,
Json.NET&#39;s default behavor).</p>
<p>Json.NET serializes .NET classes that implement IEnumerable as an
JSON array populated with the IEnumerable values. Placing the JsonPropertyAttribute overrides this
behavor and forces the serializer to serialize the class's fields and properties.</p>
<h5>JsonPropertyAttribute</h5>
<p>Allows the name of the serialized member to be customized. The attribute also indicates that a member should be serialized when member serialization is set to opt-in.</p>
<h5>JsonIgnoreAttribute</h5>
<p>Excludes a field or property from serialization.</p>
<h5>JsonConverterAttribute</h5>
<p>The JsonConverterAttribute specifies which JsonSerializer is used to convert an object.</p>
<p>The attribute can be placed on a class or a member. When placed on a class the JsonConverter
specified by the attribute will be the default way of serializing that class. When the attribute is on a field
or property then the specified JsonConverter will always be used to serialize that value.</p>
<p>The priority of which JsonConverter is used is member attribute then class attribute and
finally any converters passed to the JsonSerializer.</p>
<div class="overflowpanel"> <div class="code">
<div style="font-family: Courier New; font-size: 10pt; color: black;">
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MemberConverterClass</span></pre>
<pre style="margin: 0px;">{</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> DefaultConverter { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonConverter</span>(<span style="color: blue;">typeof</span>(<span style="color: #2b91af;">IsoDateTimeConverter</span>))]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> MemberConverter { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
</div></div>
<p>This example shows the JsonConverterAttribute being applied to a property.</p>
<div class="overflowpanel"> <div class="code">
<div style="font-family: Courier New; font-size: 10pt; color: black;">
<pre style="margin: 0px;"><span style="color: #2b91af;">DateTime</span> date = <span style="color: #2b91af;">Convert</span>.ToDateTime(<span style="color: #a31515;">"1970-01-01T00:00:00Z"</span>).ToUniversalTime();</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: #2b91af;">MemberConverterClass</span> c = <span style="color: blue;">new</span> <span style="color: #2b91af;">MemberConverterClass</span></pre>
<pre style="margin: 0px;">&nbsp; {</pre>
<pre style="margin: 0px;">&nbsp; &nbsp; DefaultConverter = date,</pre>
<pre style="margin: 0px;">&nbsp; &nbsp; MemberConverter = date</pre>
<pre style="margin: 0px;">&nbsp; };</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: blue;">string</span> json = <span style="color: #2b91af;">JsonConvert</span>.SerializeObject(c, <span style="color: #2b91af;">Formatting</span>.Indented);</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: #2b91af;">Console</span>.WriteLine(json);</pre>
<pre style="margin: 0px;"><span style="color: green;">//{</span></pre>
<pre style="margin: 0px;"><span style="color: green;">//&nbsp; "DefaultConverter": "\/Date(0)\/",</span></pre>
<pre style="margin: 0px;"><span style="color: green;">//&nbsp; "MemberConverter": "1970-01-01T00:00:00Z"</span></pre>
<pre style="margin: 0px;"><span style="color: green;">//}</span></pre>
</div>
</div></div>
<div id="footer">
</div>
</div>
</body>
</html>
-80
View File
@@ -98,87 +98,7 @@ the member's DefaultValueAttribute. Include or ignore.</p>
<h5>TypeNameHandling</h5>
<p>Controls how .NET type names are used when serializing and deserializing JSON. If
type names are SDFSDFSDF</p>
<h3>Serialization Attributes</h3>
<p>There are a number of attributes that can be placed on a class to control how it is serialized.</p>
<p>Note that as well as using the built-in Json.NET attributes, Json.NET also looks for the
<a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> and
<a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataMember</a> attributes when determining how JSON is to be serialized and deserialized. If both are present the Json.NET serialization attributes take precedence.</p>
<div class="overflowpanel"> <div class="code">
<div style="font-family: Courier New; font-size: 10pt; color: black;">
<pre style="margin: 0px;">[<span style="color: #2b91af;">JsonObject</span>(<span style="color: #2b91af;">MemberSerialization</span>.OptIn)]</pre>
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Person</span></pre>
<pre style="margin: 0px;">{</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// "John Smith"</span></pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonProperty</span>]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">string</span> Name { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// "2000-12-15T22:11:03"</span></pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonProperty</span>]</pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonConverter</span>(<span style="color: blue;">typeof</span>(<span style="color: #2b91af;">IsoDateTimeConverter</span>))]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> BirthDate { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// new Date(976918263055)</span></pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonProperty</span>]</pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonConverter</span>(<span style="color: blue;">typeof</span>(<span style="color: #2b91af;">JavaScriptDateTimeConverter</span>))]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> LastModified { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: green;">// not serialized</span></pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">string</span> Department { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
</div></div>
<h5>JsonObjectAttribute</h5>
<p>The MemberSerialization flag on this attribute specifies whether member serialization is opt-in (a member must have the JsonProperty or DataMember attribute to be serialized) or opt-out (everything is serialized by default but can be ignored with the JsonIgnoreAttribute).</p>
<p>.NET classes that implement IEnumerable are automatically serialized as an array, populated with the IEnumerable values. Placing the JsonPropertyAttribute will override this and force the serializer to serialize the class's fields and properties.</p>
<h5>JsonPropertyAttribute</h5>
<p>Allows the name of the serialized member to be customized. The attribute also indicates that a member should be serialized when member serialization is set to opt-in.</p>
<h5>JsonIgnoreAttribute</h5>
<p>Excludes a field or property from serialization.</p>
<h5>JsonConverterAttribute</h5>
<p>The JsonConverterAttribute specifies which JsonSerializer is used to convert an object.</p>
<p>The attribute can be placed on a class or a member. When placed on a class the JsonConverter
specified by the attribute will be the default way of serializing that class. When the attribute is on a field
or property then the specified JsonConverter will always be used to serialize that value.</p>
<p>The priority of which JsonConverter is used is member attribute then class attribute and
finally any converters passed to the JsonSerializer.</p>
<div class="overflowpanel"> <div class="code">
<div style="font-family: Courier New; font-size: 10pt; color: black;">
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MemberConverterClass</span></pre>
<pre style="margin: 0px;">{</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> DefaultConverter { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp; [<span style="color: #2b91af;">JsonConverter</span>(<span style="color: blue;">typeof</span>(<span style="color: #2b91af;">IsoDateTimeConverter</span>))]</pre>
<pre style="margin: 0px;">&nbsp; <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> MemberConverter { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
</div></div>
<p>This example shows the JsonConverterAttribute being applied to a property.</p>
<div class="overflowpanel"> <div class="code">
<div style="font-family: Courier New; font-size: 10pt; color: black;">
<pre style="margin: 0px;"><span style="color: #2b91af;">DateTime</span> date = <span style="color: #2b91af;">Convert</span>.ToDateTime(<span style="color: #a31515;">"1970-01-01T00:00:00Z"</span>).ToUniversalTime();</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: #2b91af;">MemberConverterClass</span> c = <span style="color: blue;">new</span> <span style="color: #2b91af;">MemberConverterClass</span></pre>
<pre style="margin: 0px;">&nbsp; {</pre>
<pre style="margin: 0px;">&nbsp; &nbsp; DefaultConverter = date,</pre>
<pre style="margin: 0px;">&nbsp; &nbsp; MemberConverter = date</pre>
<pre style="margin: 0px;">&nbsp; };</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: blue;">string</span> json = <span style="color: #2b91af;">JsonConvert</span>.SerializeObject(c, <span style="color: #2b91af;">Formatting</span>.Indented);</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: #2b91af;">Console</span>.WriteLine(json);</pre>
<pre style="margin: 0px;"><span style="color: green;">//{</span></pre>
<pre style="margin: 0px;"><span style="color: green;">//&nbsp; "DefaultConverter": "\/Date(0)\/",</span></pre>
<pre style="margin: 0px;"><span style="color: green;">//&nbsp; "MemberConverter": "1970-01-01T00:00:00Z"</span></pre>
<pre style="margin: 0px;"><span style="color: green;">//}</span></pre>
</div>
</div></div>
<h3>JsonConverters</h3>
<p>JsonConverters allows JSON to be manually written during serialization and read during deserialization. This is useful for particularly complex JSON structures or for when you want to change how a type is serialized.</p>
+1
View File
@@ -23,6 +23,7 @@
<contentItem sourcePath=".\PreserveObjectReferences.html" destPath="" excludeItems="False" />
<contentItem sourcePath=".\ContractResolver.html" destPath="" excludeItems="False" />
<contentItem sourcePath=".\SerializationCallbacks.html" destPath="" excludeItems="False" />
<contentItem sourcePath=".\SerializationAttributes.html" destPath="" excludeItems="False" />
</additionalContent>
<ProjectSummary />
<MissingTags>Summary, Parameter, Returns, AutoDocumentCtors, Namespace, TypeParameter</MissingTags>
+2 -1
View File
@@ -2,9 +2,10 @@
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode title="Introduction" url=".\Introduction.html" isDefault="true" />
<siteMapNode title="Serializing and deserializing JSON" url=".\SerializingJSON.html">
<siteMapNode title="Customizing JSON serialization with attributes" url=".\SerializationAttributes.html" />
<siteMapNode title="Serializing dates in JSON" url=".\DatesInJSON.html" />
<siteMapNode title="Serialization Callbacks" url=".\SerializationCallbacks.html" />
<siteMapNode title="Preserve Object References" url=".\PreserveObjectReferences.html" />
<siteMapNode title="Serialization and Preserving Object References" url=".\PreserveObjectReferences.html" />
<siteMapNode title="CustomCreationConverter" url=".\CustomCreationConverter.html" />
<siteMapNode title="Contract Resolvers" url=".\ContractResolver.html" />
</siteMapNode>
-242
View File
@@ -1,242 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3053
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()]
[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("EntityDataModel", "PurchasePurchaseLine", "Purchase", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Newtonsoft.Json.Tests.Purchase), "PurchaseLine", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Newtonsoft.Json.Tests.PurchaseLine))]
// Original file name:
// Generation date: 7/09/2008 7:58:08 p.m.
namespace Newtonsoft.Json.Tests
{
/// <summary>
/// There are no comments for EntityDataModelContainer in the schema.
/// </summary>
public partial class EntityDataModelContainer : global::System.Data.Objects.ObjectContext
{
/// <summary>
/// Initializes a new EntityDataModelContainer object using the connection string found in the 'EntityDataModelContainer' section of the application configuration file.
/// </summary>
public EntityDataModelContainer() :
base("name=EntityDataModelContainer", "EntityDataModelContainer")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new EntityDataModelContainer object.
/// </summary>
public EntityDataModelContainer(string connectionString) :
base(connectionString, "EntityDataModelContainer")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new EntityDataModelContainer object.
/// </summary>
public EntityDataModelContainer(global::System.Data.EntityClient.EntityConnection connection) :
base(connection, "EntityDataModelContainer")
{
this.OnContextCreated();
}
partial void OnContextCreated();
/// <summary>
/// There are no comments for PurchaseSet in the schema.
/// </summary>
public global::System.Data.Objects.ObjectQuery<Purchase> PurchaseSet
{
get
{
if ((this._PurchaseSet == null))
{
this._PurchaseSet = base.CreateQuery<Purchase>("[PurchaseSet]");
}
return this._PurchaseSet;
}
}
private global::System.Data.Objects.ObjectQuery<Purchase> _PurchaseSet;
/// <summary>
/// There are no comments for PurchaseLineSet in the schema.
/// </summary>
public global::System.Data.Objects.ObjectQuery<PurchaseLine> PurchaseLineSet
{
get
{
if ((this._PurchaseLineSet == null))
{
this._PurchaseLineSet = base.CreateQuery<PurchaseLine>("[PurchaseLineSet]");
}
return this._PurchaseLineSet;
}
}
private global::System.Data.Objects.ObjectQuery<PurchaseLine> _PurchaseLineSet;
/// <summary>
/// There are no comments for PurchaseSet in the schema.
/// </summary>
public void AddToPurchaseSet(Purchase purchase)
{
base.AddObject("PurchaseSet", purchase);
}
/// <summary>
/// There are no comments for PurchaseLineSet in the schema.
/// </summary>
public void AddToPurchaseLineSet(PurchaseLine purchaseLine)
{
base.AddObject("PurchaseLineSet", purchaseLine);
}
}
/// <summary>
/// There are no comments for EntityDataModel.Purchase in the schema.
/// </summary>
/// <KeyProperties>
/// Id
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="EntityDataModel", Name="Purchase")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Purchase : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Purchase object.
/// </summary>
/// <param name="id">Initial value of Id.</param>
public static Purchase CreatePurchase(int id)
{
Purchase purchase = new Purchase();
purchase.Id = id;
return purchase;
}
/// <summary>
/// There are no comments for Property Id in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int Id
{
get
{
return this._Id;
}
set
{
this.OnIdChanging(value);
this.ReportPropertyChanging("Id");
this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("Id");
this.OnIdChanged();
}
}
private int _Id;
partial void OnIdChanging(int value);
partial void OnIdChanged();
/// <summary>
/// There are no comments for PurchaseLine in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("EntityDataModel", "PurchasePurchaseLine", "PurchaseLine")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityCollection<PurchaseLine> PurchaseLine
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<PurchaseLine>("EntityDataModel.PurchasePurchaseLine", "PurchaseLine");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<PurchaseLine>("EntityDataModel.PurchasePurchaseLine", "PurchaseLine", value);
}
}
}
}
/// <summary>
/// There are no comments for EntityDataModel.PurchaseLine in the schema.
/// </summary>
/// <KeyProperties>
/// Id
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="EntityDataModel", Name="PurchaseLine")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class PurchaseLine : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new PurchaseLine object.
/// </summary>
/// <param name="id">Initial value of Id.</param>
public static PurchaseLine CreatePurchaseLine(int id)
{
PurchaseLine purchaseLine = new PurchaseLine();
purchaseLine.Id = id;
return purchaseLine;
}
/// <summary>
/// There are no comments for Property Id in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int Id
{
get
{
return this._Id;
}
set
{
this.OnIdChanging(value);
this.ReportPropertyChanging("Id");
this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("Id");
this.OnIdChanged();
}
}
private int _Id;
partial void OnIdChanging(int value);
partial void OnIdChanged();
/// <summary>
/// There are no comments for Purchase in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("EntityDataModel", "PurchasePurchaseLine", "Purchase")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public Purchase Purchase
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Purchase>("EntityDataModel.PurchasePurchaseLine", "Purchase").Value;
}
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Purchase>("EntityDataModel.PurchasePurchaseLine", "Purchase").Value = value;
}
}
/// <summary>
/// There are no comments for Purchase in the schema.
/// </summary>
[global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityReference<Purchase> PurchaseReference
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Purchase>("EntityDataModel.PurchasePurchaseLine", "Purchase");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Purchase>("EntityDataModel.PurchasePurchaseLine", "Purchase", value);
}
}
}
}
}
@@ -1,67 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl" Namespace="EntityDataModel.Target" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005">
<EntityContainer Name="EntityDataModelTargetContainer" >
</EntityContainer>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2006/04/edm" Namespace="EntityDataModel" Alias="Self">
<EntityContainer Name="EntityDataModelContainer" >
<EntitySet Name="PurchaseSet" EntityType="EntityDataModel.Purchase" />
<EntitySet Name="PurchaseLineSet" EntityType="EntityDataModel.PurchaseLine" />
<AssociationSet Name="PurchasePurchaseLine" Association="EntityDataModel.PurchasePurchaseLine">
<End Role="Purchase" EntitySet="PurchaseSet" />
<End Role="PurchaseLine" EntitySet="PurchaseLineSet" /></AssociationSet></EntityContainer>
<EntityType Name="Purchase">
<Key>
<PropertyRef Name="Id" /></Key>
<Property Name="Id" Type="Int32" Nullable="false" />
<NavigationProperty Name="PurchaseLine" Relationship="EntityDataModel.PurchasePurchaseLine" FromRole="Purchase" ToRole="PurchaseLine" /></EntityType>
<EntityType Name="PurchaseLine">
<Key>
<PropertyRef Name="Id" /></Key>
<Property Name="Id" Type="Int32" Nullable="false" />
<NavigationProperty Name="Purchase" Relationship="EntityDataModel.PurchasePurchaseLine" FromRole="PurchaseLine" ToRole="Purchase" /></EntityType>
<Association Name="PurchasePurchaseLine">
<End Type="EntityDataModel.Purchase" Role="Purchase" Multiplicity="1" />
<End Type="EntityDataModel.PurchaseLine" Role="PurchaseLine" Multiplicity="*" /></Association></Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS" Space="C-S">
<Alias Key="Model" Value="EntityDataModel" />
<Alias Key="Target" Value="EntityDataModel.Target" />
<EntityContainerMapping CdmEntityContainer="EntityDataModelContainer" StorageEntityContainer="EntityDataModelTargetContainer">
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram Name="EntityDataModel" >
<EntityTypeShape EntityType="EntityDataModel.Purchase" Width="1.5" PointX="2.125" PointY="0.875" Height="1.211080729166667" />
<EntityTypeShape EntityType="EntityDataModel.PurchaseLine" Width="1.5" PointX="3.625" PointY="3" Height="1.0187792968749996" />
<AssociationConnector Association="EntityDataModel.PurchasePurchaseLine">
<ConnectorPoint PointX="2.84375" PointY="2.086080729166667" />
<ConnectorPoint PointX="2.84375" PointY="3.6055403645833333" />
<ConnectorPoint PointX="3.625" PointY="3.6055403645833333" /></AssociationConnector></Diagram></edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Schema;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests
{
public class ExceptionTests : TestFixtureBase
{
[Test]
public void JsonSerializationException()
{
JsonSerializationException exception = new JsonSerializationException();
Assert.AreEqual("Exception of type 'Newtonsoft.Json.JsonSerializationException' was thrown.", exception.Message);
exception = new JsonSerializationException("Message!");
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual(null, exception.InnerException);
exception = new JsonSerializationException("Message!", new Exception("Inner!"));
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual("Inner!", exception.InnerException.Message);
}
[Test]
public void JsonWriterException()
{
JsonWriterException exception = new JsonWriterException();
Assert.AreEqual("Exception of type 'Newtonsoft.Json.JsonWriterException' was thrown.", exception.Message);
exception = new JsonWriterException("Message!");
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual(null, exception.InnerException);
exception = new JsonWriterException("Message!", new Exception("Inner!"));
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual("Inner!", exception.InnerException.Message);
}
[Test]
public void JsonReaderException()
{
JsonReaderException exception = new JsonReaderException();
Assert.AreEqual("Exception of type 'Newtonsoft.Json.JsonReaderException' was thrown.", exception.Message);
exception = new JsonReaderException("Message!");
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual(null, exception.InnerException);
exception = new JsonReaderException("Message!", new Exception("Inner!"));
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual("Inner!", exception.InnerException.Message);
}
[Test]
public void JsonSchemaException()
{
JsonSchemaException exception = new JsonSchemaException();
Assert.AreEqual("Exception of type 'Newtonsoft.Json.Schema.JsonSchemaException' was thrown.", exception.Message);
exception = new JsonSchemaException("Message!");
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual(null, exception.InnerException);
exception = new JsonSchemaException("Message!", new Exception("Inner!"));
Assert.AreEqual("Message!", exception.Message);
Assert.AreEqual("Inner!", exception.InnerException.Message);
}
}
}
@@ -0,0 +1,449 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3074
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()]
[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DataServicesTestDatabaseModel", "FK_File_Folder", "Folder", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Newtonsoft.Json.Tests.Folder), "File", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Newtonsoft.Json.Tests.File))]
[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DataServicesTestDatabaseModel", "FK_Folder_Folder", "Folder", global::System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(Newtonsoft.Json.Tests.Folder), "Folder1", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Newtonsoft.Json.Tests.Folder))]
// Original file name:
// Generation date: 26/07/2009 4:51:53 p.m.
namespace Newtonsoft.Json.Tests
{
/// <summary>
/// There are no comments for DataServicesTestDatabaseEntities in the schema.
/// </summary>
public partial class DataServicesTestDatabaseEntities : global::System.Data.Objects.ObjectContext
{
/// <summary>
/// Initializes a new DataServicesTestDatabaseEntities object using the connection string found in the 'DataServicesTestDatabaseEntities' section of the application configuration file.
/// </summary>
public DataServicesTestDatabaseEntities() :
base("name=DataServicesTestDatabaseEntities", "DataServicesTestDatabaseEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new DataServicesTestDatabaseEntities object.
/// </summary>
public DataServicesTestDatabaseEntities(string connectionString) :
base(connectionString, "DataServicesTestDatabaseEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new DataServicesTestDatabaseEntities object.
/// </summary>
public DataServicesTestDatabaseEntities(global::System.Data.EntityClient.EntityConnection connection) :
base(connection, "DataServicesTestDatabaseEntities")
{
this.OnContextCreated();
}
partial void OnContextCreated();
/// <summary>
/// There are no comments for File in the schema.
/// </summary>
public global::System.Data.Objects.ObjectQuery<File> File
{
get
{
if ((this._File == null))
{
this._File = base.CreateQuery<File>("[File]");
}
return this._File;
}
}
private global::System.Data.Objects.ObjectQuery<File> _File;
/// <summary>
/// There are no comments for Folder in the schema.
/// </summary>
public global::System.Data.Objects.ObjectQuery<Folder> Folder
{
get
{
if ((this._Folder == null))
{
this._Folder = base.CreateQuery<Folder>("[Folder]");
}
return this._Folder;
}
}
private global::System.Data.Objects.ObjectQuery<Folder> _Folder;
/// <summary>
/// There are no comments for File in the schema.
/// </summary>
public void AddToFile(File file)
{
base.AddObject("File", file);
}
/// <summary>
/// There are no comments for Folder in the schema.
/// </summary>
public void AddToFolder(Folder folder)
{
base.AddObject("Folder", folder);
}
}
/// <summary>
/// There are no comments for DataServicesTestDatabaseModel.File in the schema.
/// </summary>
/// <KeyProperties>
/// FileId
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DataServicesTestDatabaseModel", Name="File")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class File : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new File object.
/// </summary>
/// <param name="fileId">Initial value of FileId.</param>
/// <param name="name">Initial value of Name.</param>
/// <param name="description">Initial value of Description.</param>
/// <param name="createdDate">Initial value of CreatedDate.</param>
public static File CreateFile(global::System.Guid fileId, string name, string description, global::System.DateTime createdDate)
{
File file = new File();
file.FileId = fileId;
file.Name = name;
file.Description = description;
file.CreatedDate = createdDate;
return file;
}
/// <summary>
/// There are no comments for Property FileId in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Guid FileId
{
get
{
return this._FileId;
}
set
{
this.OnFileIdChanging(value);
this.ReportPropertyChanging("FileId");
this._FileId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("FileId");
this.OnFileIdChanged();
}
}
private global::System.Guid _FileId;
partial void OnFileIdChanging(global::System.Guid value);
partial void OnFileIdChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Property Description in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Description
{
get
{
return this._Description;
}
set
{
this.OnDescriptionChanging(value);
this.ReportPropertyChanging("Description");
this._Description = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
this.ReportPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
private string _Description;
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
/// <summary>
/// There are no comments for Property CreatedDate in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.DateTime CreatedDate
{
get
{
return this._CreatedDate;
}
set
{
this.OnCreatedDateChanging(value);
this.ReportPropertyChanging("CreatedDate");
this._CreatedDate = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("CreatedDate");
this.OnCreatedDateChanged();
}
}
private global::System.DateTime _CreatedDate;
partial void OnCreatedDateChanging(global::System.DateTime value);
partial void OnCreatedDateChanged();
/// <summary>
/// There are no comments for Folder in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_File_Folder", "Folder")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public Folder Folder
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_File_Folder", "Folder").Value;
}
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_File_Folder", "Folder").Value = value;
}
}
/// <summary>
/// There are no comments for Folder in the schema.
/// </summary>
[global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityReference<Folder> FolderReference
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_File_Folder", "Folder");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_File_Folder", "Folder", value);
}
}
}
}
/// <summary>
/// There are no comments for DataServicesTestDatabaseModel.Folder in the schema.
/// </summary>
/// <KeyProperties>
/// FolderId
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DataServicesTestDatabaseModel", Name="Folder")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Folder : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Folder object.
/// </summary>
/// <param name="folderId">Initial value of FolderId.</param>
/// <param name="name">Initial value of Name.</param>
/// <param name="createdDate">Initial value of CreatedDate.</param>
public static Folder CreateFolder(global::System.Guid folderId, string name, global::System.DateTime createdDate)
{
Folder folder = new Folder();
folder.FolderId = folderId;
folder.Name = name;
folder.CreatedDate = createdDate;
return folder;
}
/// <summary>
/// There are no comments for Property FolderId in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Guid FolderId
{
get
{
return this._FolderId;
}
set
{
this.OnFolderIdChanging(value);
this.ReportPropertyChanging("FolderId");
this._FolderId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("FolderId");
this.OnFolderIdChanged();
}
}
private global::System.Guid _FolderId;
partial void OnFolderIdChanging(global::System.Guid value);
partial void OnFolderIdChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Property Description in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Description
{
get
{
return this._Description;
}
set
{
this.OnDescriptionChanging(value);
this.ReportPropertyChanging("Description");
this._Description = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
private string _Description;
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
/// <summary>
/// There are no comments for Property CreatedDate in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.DateTime CreatedDate
{
get
{
return this._CreatedDate;
}
set
{
this.OnCreatedDateChanging(value);
this.ReportPropertyChanging("CreatedDate");
this._CreatedDate = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("CreatedDate");
this.OnCreatedDateChanged();
}
}
private global::System.DateTime _CreatedDate;
partial void OnCreatedDateChanging(global::System.DateTime value);
partial void OnCreatedDateChanged();
/// <summary>
/// There are no comments for Files in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_File_Folder", "File")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityCollection<File> Files
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<File>("DataServicesTestDatabaseModel.FK_File_Folder", "File");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<File>("DataServicesTestDatabaseModel.FK_File_Folder", "File", value);
}
}
}
/// <summary>
/// There are no comments for ChildFolders in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_Folder_Folder", "Folder1")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityCollection<Folder> ChildFolders
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder1");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder1", value);
}
}
}
/// <summary>
/// There are no comments for ParentFolder in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_Folder_Folder", "Folder")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public Folder ParentFolder
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder").Value;
}
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder").Value = value;
}
}
/// <summary>
/// There are no comments for ParentFolder in the schema.
/// </summary>
[global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityReference<Folder> ParentFolderReference
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder", value);
}
}
}
}
}
@@ -0,0 +1,184 @@
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="DataServicesTestDatabaseModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
<EntityContainer Name="DataServicesTestDatabaseModelStoreContainer">
<EntitySet Name="File" EntityType="DataServicesTestDatabaseModel.Store.File" store:Type="Tables" Schema="dbo" />
<EntitySet Name="Folder" EntityType="DataServicesTestDatabaseModel.Store.Folder" store:Type="Tables" Schema="dbo" />
<AssociationSet Name="FK_File_Folder" Association="DataServicesTestDatabaseModel.Store.FK_File_Folder">
<End Role="Folder" EntitySet="Folder" />
<End Role="File" EntitySet="File" />
</AssociationSet>
<AssociationSet Name="FK_Folder_Folder" Association="DataServicesTestDatabaseModel.Store.FK_Folder_Folder">
<End Role="Folder" EntitySet="Folder" />
<End Role="Folder1" EntitySet="Folder" />
</AssociationSet>
</EntityContainer>
<EntityType Name="File">
<Key>
<PropertyRef Name="FileId" />
</Key>
<Property Name="FileId" Type="uniqueidentifier" Nullable="false" />
<Property Name="Name" Type="nvarchar" Nullable="false" MaxLength="200" />
<Property Name="Description" Type="nvarchar" Nullable="false" MaxLength="200" />
<Property Name="CreatedDate" Type="datetime" Nullable="false" />
<Property Name="FolderId" Type="uniqueidentifier" Nullable="false" />
</EntityType>
<EntityType Name="Folder">
<Key>
<PropertyRef Name="FolderId" />
</Key>
<Property Name="FolderId" Type="uniqueidentifier" Nullable="false" />
<Property Name="Name" Type="nvarchar" Nullable="false" MaxLength="200" />
<Property Name="Description" Type="nvarchar" Nullable="false" MaxLength="200" />
<Property Name="CreatedDate" Type="datetime" Nullable="false" />
<Property Name="ParentFolderId" Type="uniqueidentifier" />
</EntityType>
<Association Name="FK_File_Folder">
<End Role="Folder" Type="DataServicesTestDatabaseModel.Store.Folder" Multiplicity="1" />
<End Role="File" Type="DataServicesTestDatabaseModel.Store.File" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Folder">
<PropertyRef Name="FolderId" />
</Principal>
<Dependent Role="File">
<PropertyRef Name="FolderId" />
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_Folder_Folder">
<End Role="Folder" Type="DataServicesTestDatabaseModel.Store.Folder" Multiplicity="0..1" />
<End Role="Folder1" Type="DataServicesTestDatabaseModel.Store.Folder" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Folder">
<PropertyRef Name="FolderId" />
</Principal>
<Dependent Role="Folder1">
<PropertyRef Name="ParentFolderId" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="DataServicesTestDatabaseModel" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2006/04/edm">
<EntityContainer Name="DataServicesTestDatabaseEntities">
<EntitySet Name="File" EntityType="DataServicesTestDatabaseModel.File" />
<EntitySet Name="Folder" EntityType="DataServicesTestDatabaseModel.Folder" />
<AssociationSet Name="FK_File_Folder" Association="DataServicesTestDatabaseModel.FK_File_Folder">
<End Role="Folder" EntitySet="Folder" />
<End Role="File" EntitySet="File" />
</AssociationSet>
<AssociationSet Name="FK_Folder_Folder" Association="DataServicesTestDatabaseModel.FK_Folder_Folder">
<End Role="Folder" EntitySet="Folder" />
<End Role="Folder1" EntitySet="Folder" />
</AssociationSet>
</EntityContainer>
<EntityType Name="File">
<Key>
<PropertyRef Name="FileId" />
</Key>
<Property Name="FileId" Type="Guid" Nullable="false" />
<Property Name="Name" Type="String" Nullable="false" MaxLength="200" Unicode="true" FixedLength="false" />
<Property Name="Description" Type="String" Nullable="false" MaxLength="200" Unicode="true" FixedLength="false" />
<Property Name="CreatedDate" Type="DateTime" Nullable="false" />
<NavigationProperty Name="Folder" Relationship="DataServicesTestDatabaseModel.FK_File_Folder" FromRole="File" ToRole="Folder" />
</EntityType>
<EntityType Name="Folder">
<Key>
<PropertyRef Name="FolderId" />
</Key>
<Property Name="FolderId" Type="Guid" Nullable="false" />
<Property Name="Name" Type="String" Nullable="false" MaxLength="200" Unicode="true" FixedLength="false" />
<Property Name="Description" Type="String" Nullable="false" MaxLength="200" Unicode="true" FixedLength="false" />
<Property Name="CreatedDate" Type="DateTime" Nullable="false" />
<NavigationProperty Name="Files" Relationship="DataServicesTestDatabaseModel.FK_File_Folder" FromRole="Folder" ToRole="File" />
<NavigationProperty Name="ChildFolders" Relationship="DataServicesTestDatabaseModel.FK_Folder_Folder" FromRole="Folder" ToRole="Folder1" />
<NavigationProperty Name="ParentFolder" Relationship="DataServicesTestDatabaseModel.FK_Folder_Folder" FromRole="Folder1" ToRole="Folder" />
</EntityType>
<Association Name="FK_File_Folder">
<End Role="Folder" Type="DataServicesTestDatabaseModel.Folder" Multiplicity="1" />
<End Role="File" Type="DataServicesTestDatabaseModel.File" Multiplicity="*" />
</Association>
<Association Name="FK_Folder_Folder">
<End Role="Folder" Type="DataServicesTestDatabaseModel.Folder" Multiplicity="0..1" />
<End Role="Folder1" Type="DataServicesTestDatabaseModel.Folder" Multiplicity="*" />
</Association>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS">
<EntityContainerMapping StorageEntityContainer="DataServicesTestDatabaseModelStoreContainer" CdmEntityContainer="DataServicesTestDatabaseEntities">
<EntitySetMapping Name="File">
<EntityTypeMapping TypeName="IsTypeOf(DataServicesTestDatabaseModel.File)">
<MappingFragment StoreEntitySet="File">
<ScalarProperty Name="FileId" ColumnName="FileId" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="Description" ColumnName="Description" />
<ScalarProperty Name="CreatedDate" ColumnName="CreatedDate" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="Folder">
<EntityTypeMapping TypeName="IsTypeOf(DataServicesTestDatabaseModel.Folder)">
<MappingFragment StoreEntitySet="Folder">
<ScalarProperty Name="FolderId" ColumnName="FolderId" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="Description" ColumnName="Description" />
<ScalarProperty Name="CreatedDate" ColumnName="CreatedDate" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="FK_File_Folder" TypeName="DataServicesTestDatabaseModel.FK_File_Folder" StoreEntitySet="File">
<EndProperty Name="Folder">
<ScalarProperty Name="FolderId" ColumnName="FolderId" />
</EndProperty>
<EndProperty Name="File">
<ScalarProperty Name="FileId" ColumnName="FileId" />
</EndProperty>
</AssociationSetMapping>
<AssociationSetMapping Name="FK_Folder_Folder" TypeName="DataServicesTestDatabaseModel.FK_Folder_Folder" StoreEntitySet="Folder">
<EndProperty Name="Folder">
<ScalarProperty Name="FolderId" ColumnName="ParentFolderId" />
</EndProperty>
<EndProperty Name="Folder1">
<ScalarProperty Name="FolderId" ColumnName="FolderId" />
</EndProperty>
<Condition ColumnName="ParentFolderId" IsNull="false" />
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram Name="FileSystemEntityModel">
<EntityTypeShape EntityType="DataServicesTestDatabaseModel.File" Width="1.5" PointX="3" PointY="1.125" Height="1.9802864583333335" IsExpanded="true" />
<EntityTypeShape EntityType="DataServicesTestDatabaseModel.Folder" Width="1.5" PointX="0.75" PointY="1" Height="2.3648893229166665" IsExpanded="true" />
<AssociationConnector Association="DataServicesTestDatabaseModel.FK_File_Folder" ManuallyRouted="false">
<ConnectorPoint PointX="2.25" PointY="2.1151432291666667" />
<ConnectorPoint PointX="3" PointY="2.1151432291666667" /></AssociationConnector>
<AssociationConnector Association="DataServicesTestDatabaseModel.FK_Folder_Folder" ManuallyRouted="false">
<ConnectorPoint PointX="1.2819230769230767" PointY="3.3648893229166665" />
<ConnectorPoint PointX="1.2819230769230767" PointY="3.6148893229166665" />
<ConnectorPoint PointX="1.7284615384615383" PointY="3.6148893229166665" />
<ConnectorPoint PointX="1.7284615384615383" PointY="3.3648893229166665" /></AssociationConnector></Diagram></edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests
{
public class JsonArrayAttributeTests : TestFixtureBase
{
[Test]
public void IsReferenceTest()
{
JsonPropertyAttribute attribute = new JsonPropertyAttribute();
Assert.AreEqual(null, attribute._isReference);
Assert.AreEqual(false, attribute.IsReference);
attribute.IsReference = false;
Assert.AreEqual(false, attribute._isReference);
Assert.AreEqual(false, attribute.IsReference);
attribute.IsReference = true;
Assert.AreEqual(true, attribute._isReference);
Assert.AreEqual(true, attribute.IsReference);
}
[Test]
public void NullValueHandlingTest()
{
JsonPropertyAttribute attribute = new JsonPropertyAttribute();
Assert.AreEqual(null, attribute._nullValueHandling);
Assert.AreEqual(NullValueHandling.Include, attribute.NullValueHandling);
attribute.NullValueHandling = NullValueHandling.Ignore;
Assert.AreEqual(NullValueHandling.Ignore, attribute._nullValueHandling);
Assert.AreEqual(NullValueHandling.Ignore, attribute.NullValueHandling);
}
[Test]
public void DefaultValueHandlingTest()
{
JsonPropertyAttribute attribute = new JsonPropertyAttribute();
Assert.AreEqual(null, attribute._defaultValueHandling);
Assert.AreEqual(DefaultValueHandling.Include, attribute.DefaultValueHandling);
attribute.DefaultValueHandling = DefaultValueHandling.Ignore;
Assert.AreEqual(DefaultValueHandling.Ignore, attribute._defaultValueHandling);
Assert.AreEqual(DefaultValueHandling.Ignore, attribute.DefaultValueHandling);
}
[Test]
public void ReferenceLoopHandlingTest()
{
JsonPropertyAttribute attribute = new JsonPropertyAttribute();
Assert.AreEqual(null, attribute._defaultValueHandling);
Assert.AreEqual(ReferenceLoopHandling.Error, attribute.ReferenceLoopHandling);
attribute.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
Assert.AreEqual(ReferenceLoopHandling.Ignore, attribute._referenceLoopHandling);
Assert.AreEqual(ReferenceLoopHandling.Ignore, attribute.ReferenceLoopHandling);
}
}
}
@@ -1323,7 +1323,7 @@ keyword such as type of business.""
Person person = GetPerson();
using (FileStream fs = File.Open(@"c:\person.json", FileMode.CreateNew))
using (FileStream fs = System.IO.File.Open(@"c:\person.json", FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(fs))
using (JsonWriter jw = new JsonTextWriter(sw))
{
@@ -466,5 +466,71 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString());
}
[Test]
[ExpectedException(typeof(JsonWriterException), ExpectedMessage = "No token to close.")]
public void BadWriteEndArray()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteEndArray();
jsonWriter.WriteEndArray();
}
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Invalid JavaScript string quote character. Valid quote characters are ' and "".")]
public void InvalidQuoteChar()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.QuoteChar = '*';
}
}
[Test]
public void Indentation()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.Indentation = 5;
Assert.AreEqual(5, jsonWriter.Indentation);
jsonWriter.IndentChar = '_';
Assert.AreEqual('_', jsonWriter.IndentChar);
jsonWriter.QuoteName = true;
Assert.AreEqual(true, jsonWriter.QuoteName);
jsonWriter.QuoteChar = '\'';
Assert.AreEqual('\'', jsonWriter.QuoteChar);
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("propertyName");
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteEndObject();
}
string expected = @"{
_____'propertyName': NaN
}";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
}
}
@@ -68,6 +68,7 @@
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
@@ -72,6 +72,7 @@
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
@@ -86,6 +86,13 @@
<Compile Include="Converters\BinaryConverterTests.cs" />
<Compile Include="Converters\CustomCreationConverterTests.cs" />
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="FileSystemEntityModel.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>FileSystemEntityModel.edmx</DependentUpon>
</Compile>
<Compile Include="JsonArrayAttributeTests.cs" />
<Compile Include="ExceptionTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="LinqToSql\Department.cs" />
<Compile Include="LinqToSql\DepartmentConverter.cs" />
@@ -98,6 +105,7 @@
</Compile>
<Compile Include="LinqToSql\LinqToSqlClassesSerializationTests.cs" />
<Compile Include="LinqToSql\Person.cs" />
<Compile Include="Serialization\EntitiesSerializationTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
@@ -201,6 +209,10 @@
<Service Include="{3259AA49-8AA1-44D3-9025-A0B520596A8C}" />
</ItemGroup>
<ItemGroup>
<EntityDeploy Include="FileSystemEntityModel.edmx">
<Generator>EntityModelCodeGenerator</Generator>
<LastGenOutput>FileSystemEntityModel.Designer.cs</LastGenOutput>
</EntityDeploy>
<None Include="LinqToSql\LinqToSqlClasses.dbml.layout">
<DependentUpon>LinqToSqlClasses.dbml</DependentUpon>
</None>
@@ -0,0 +1,314 @@
#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 !PocketPC && !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
public class EntitiesSerializationTests : TestFixtureBase
{
[Test]
public void SerializeEntity()
{
Folder rootFolder = CreateEntitiesTestData();
string json = JsonConvert.SerializeObject(rootFolder, Formatting.Indented, new IsoDateTimeConverter());
string expected = @"{
""$id"": ""1"",
""FolderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
""Name"": ""Root folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2000-12-10T10:50:00Z"",
""Files"": [],
""ChildFolders"": [
{
""$id"": ""2"",
""FolderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
""Name"": ""Child folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2001-11-20T10:50:00Z"",
""Files"": [
{
""$id"": ""3"",
""FileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
""Name"": ""File 1"",
""Description"": ""Description!"",
""CreatedDate"": ""2002-10-30T10:50:00Z"",
""Folder"": {
""$ref"": ""2""
},
""EntityKey"": {
""$id"": ""4"",
""EntitySetName"": ""File"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FileId"",
""Type"": ""System.Guid"",
""Value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
}
]
}
}
],
""ChildFolders"": [],
""ParentFolder"": {
""$ref"": ""1""
},
""EntityKey"": {
""$id"": ""5"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
}
]
}
}
],
""ParentFolder"": null,
""EntityKey"": {
""$id"": ""6"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
}
]
}
}";
Assert.AreEqual(expected, json);
}
[Test]
public void DeserializeEntity()
{
string json = @"{
""$id"": ""1"",
""FolderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
""Name"": ""Root folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2000-12-10T10:50:00Z"",
""Files"": [],
""ChildFolders"": [
{
""$id"": ""2"",
""FolderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
""Name"": ""Child folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2001-11-20T10:50:00Z"",
""Files"": [
{
""$id"": ""3"",
""FileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
""Name"": ""File 1"",
""Description"": ""Description!"",
""CreatedDate"": ""2002-10-30T10:50:00Z"",
""Folder"": {
""$ref"": ""2""
},
""EntityKey"": {
""$id"": ""4"",
""EntitySetName"": ""File"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FileId"",
""Type"": ""System.Guid"",
""Value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
}
]
}
}
],
""ChildFolders"": [],
""ParentFolder"": {
""$ref"": ""1""
},
""EntityKey"": {
""$id"": ""5"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
}
]
}
}
],
""ParentFolder"": null,
""EntityKey"": {
""$id"": ""6"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
}
]
}
}";
Folder f = JsonConvert.DeserializeObject<Folder>(json, new IsoDateTimeConverter());
Assert.IsNotNull(f);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), f.FolderId);
Assert.AreEqual("Folder", f.EntityKey.EntitySetName);
Assert.AreEqual("DataServicesTestDatabaseEntities", f.EntityKey.EntityContainerName);
Assert.AreEqual("Folder", f.EntityKey.EntitySetName);
Assert.AreEqual(false, f.EntityKey.IsTemporary);
Assert.AreEqual(1, f.EntityKey.EntityKeyValues.Length);
Assert.AreEqual("FolderId", f.EntityKey.EntityKeyValues[0].Key);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), f.EntityKey.EntityKeyValues[0].Value);
Assert.AreEqual("Root folder", f.Name);
Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), f.CreatedDate);
Assert.AreEqual(null, f.ParentFolder);
Assert.AreEqual(1, f.ChildFolders.Count);
Folder childFolder = f.ChildFolders.ElementAt(0);
Assert.AreEqual("Child folder", childFolder.Name);
Assert.AreEqual("Description!", childFolder.Description);
Assert.AreEqual(f, childFolder.ParentFolder);
Assert.AreEqual(f, childFolder.ParentFolderReference.Value);
// is this a problem?
Assert.AreEqual(null, childFolder.ParentFolderReference.EntityKey);
}
[Test]
public void SerializeMultiValueEntityKey()
{
EntityKey e = new EntityKey("DataServicesTestDatabaseEntities.Folder",
new List<EntityKeyMember>
{
new EntityKeyMember("GuidId", new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E")),
new EntityKeyMember("IntId", int.MaxValue),
new EntityKeyMember("LongId", long.MaxValue),
new EntityKeyMember("StringId", "String!"),
new EntityKeyMember("DateTimeId", new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc))
});
string json = JsonConvert.SerializeObject(e, Formatting.Indented);
Assert.AreEqual(@"{
""$id"": ""1"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""GuidId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
},
{
""Key"": ""IntId"",
""Type"": ""System.Int32"",
""Value"": ""2147483647""
},
{
""Key"": ""LongId"",
""Type"": ""System.Int64"",
""Value"": ""9223372036854775807""
},
{
""Key"": ""StringId"",
""Type"": ""System.String"",
""Value"": ""String!""
},
{
""Key"": ""DateTimeId"",
""Type"": ""System.DateTime"",
""Value"": ""12/10/2000 10:50:00""
}
]
}", json);
EntityKey newKey = JsonConvert.DeserializeObject<EntityKey>(json);
Assert.IsFalse(ReferenceEquals(e, newKey));
Assert.AreEqual(5, newKey.EntityKeyValues.Length);
Assert.AreEqual("GuidId", newKey.EntityKeyValues[0].Key);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), newKey.EntityKeyValues[0].Value);
Assert.AreEqual("IntId", newKey.EntityKeyValues[1].Key);
Assert.AreEqual(int.MaxValue, newKey.EntityKeyValues[1].Value);
Assert.AreEqual("LongId", newKey.EntityKeyValues[2].Key);
Assert.AreEqual(long.MaxValue, newKey.EntityKeyValues[2].Value);
Assert.AreEqual("StringId", newKey.EntityKeyValues[3].Key);
Assert.AreEqual("String!", newKey.EntityKeyValues[3].Value);
Assert.AreEqual("DateTimeId", newKey.EntityKeyValues[4].Key);
Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), newKey.EntityKeyValues[4].Value);
}
private Folder CreateEntitiesTestData()
{
Folder folder = new Folder();
folder.FolderId = new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E");
folder.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.Folder", "FolderId", folder.FolderId);
folder.Name = "Root folder";
folder.Description = "Description!";
folder.CreatedDate = new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc);
Folder childFolder = new Folder();
childFolder.FolderId = new Guid("484936E2-7CBB-4592-93FF-B2103E5705E4");
childFolder.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.Folder", "FolderId", childFolder.FolderId);
childFolder.Name = "Child folder";
childFolder.Description = "Description!";
childFolder.CreatedDate = new DateTime(2001, 11, 20, 10, 50, 0, DateTimeKind.Utc);
folder.ChildFolders.Add(childFolder);
File file1 = new File();
file1.FileId = new Guid("CC76D734-49F1-4616-BB38-41514228AC6C");
file1.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.File", "FileId", file1.FileId);
file1.Name = "File 1";
file1.Description = "Description!";
file1.CreatedDate = new DateTime(2002, 10, 30, 10, 50, 0, DateTimeKind.Utc);
childFolder.Files.Add(file1);
return folder;
}
}
}
#endif
+1
View File
@@ -24,6 +24,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Doc", "Doc", "{8F9E13D9-418
Doc\LINQtoJSON.html = Doc\LINQtoJSON.html
Doc\PreserveObjectReferences.html = Doc\PreserveObjectReferences.html
Doc\ReadingWritingJSON.html = Doc\ReadingWritingJSON.html
Doc\SerializationAttributes.html = Doc\SerializationAttributes.html
Doc\SerializationCallbacks.html = Doc\SerializationCallbacks.html
Doc\SerializingJSON.html = Doc\SerializingJSON.html
Doc\styles.css = Doc\styles.css
@@ -0,0 +1,112 @@
#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 !PocketPC && !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
public class EntityKeyMemberConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
EntityKeyMember entityKeyMember = (EntityKeyMember) value;
Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;
writer.WriteStartObject();
writer.WritePropertyName("Key");
writer.WriteValue(entityKeyMember.Key);
writer.WritePropertyName("Type");
writer.WriteValue((keyType != null) ? keyType.FullName : null);
writer.WritePropertyName("Value");
if (keyType != null)
{
string valueJson;
if (JsonSerializerWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
writer.WriteValue(valueJson);
else
writer.WriteValue(entityKeyMember.Value);
}
else
{
writer.WriteNull();
}
writer.WriteEndObject();
}
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || reader.Value.ToString() != propertyName)
throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
private static void ReadAndAssert(JsonReader reader)
{
if (!reader.Read())
throw new JsonSerializationException("Unexpected end.");
}
public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
{
EntityKeyMember entityKeyMember = new EntityKeyMember();
ReadAndAssertProperty(reader, "Key");
ReadAndAssert(reader);
entityKeyMember.Key = reader.Value.ToString();
ReadAndAssertProperty(reader, "Type");
ReadAndAssert(reader);
string type = reader.Value.ToString();
Type t = Type.GetType(type);
ReadAndAssertProperty(reader, "Value");
ReadAndAssert(reader);
entityKeyMember.Value = serializer.Deserialize(reader, t);
ReadAndAssert(reader);
return entityKeyMember;
}
public override bool CanConvert(Type objectType)
{
return typeof(EntityKeyMember).IsAssignableFrom(objectType);
}
}
}
#endif
+14 -1
View File
@@ -26,6 +26,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
@@ -51,6 +52,13 @@ namespace Newtonsoft.Json
private IReferenceResolver _referenceResolver;
private SerializationBinder _binder;
private static readonly IList<JsonConverter> BuiltInConverters = new List<JsonConverter>
{
#if !PocketPC && !SILVERLIGHT
new EntityKeyMemberConverter()
#endif
};
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
@@ -388,7 +396,12 @@ namespace Newtonsoft.Json
internal bool HasMatchingConverter(Type type, out JsonConverter matchingConverter)
{
return HasMatchingConverter(_converters, type, out matchingConverter);
if (HasMatchingConverter(_converters, type, out matchingConverter))
return true;
if (HasMatchingConverter(BuiltInConverters, type, out matchingConverter))
return true;
return false;
}
internal static bool HasMatchingConverter(IList<JsonConverter> converters, Type objectType, out JsonConverter matchingConverter)
@@ -57,6 +57,7 @@
<ItemGroup>
<Compile Include="Converters\BinaryConverter.cs" />
<Compile Include="Converters\CustomCreationConverter.cs" />
<Compile Include="Converters\EntityKeyMemberConverter.cs" />
<Compile Include="Converters\StringEnumConverter.cs" />
<Compile Include="DateTimeOffset.cs" />
<Compile Include="IJsonLineInfo.cs" />
@@ -51,6 +51,7 @@
<ItemGroup>
<Compile Include="Converters\BinaryConverter.cs" />
<Compile Include="Converters\CustomCreationConverter.cs" />
<Compile Include="Converters\EntityKeyMemberConverter.cs" />
<Compile Include="Converters\IsoDateTimeConverter.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverter.cs" />
<Compile Include="Converters\JsonDateTimeSerializationMode.cs" />
@@ -72,6 +72,9 @@
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Data.Entity">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
@@ -85,6 +88,7 @@
<ItemGroup>
<Compile Include="Converters\BinaryConverter.cs" />
<Compile Include="Converters\CustomCreationConverter.cs" />
<Compile Include="Converters\EntityKeyMemberConverter.cs" />
<Compile Include="Converters\StringEnumConverter.cs" />
<Compile Include="Serialization\DefaultReferenceResolver.cs" />
<Compile Include="PreserveReferencesHandling.cs" />
@@ -205,5 +209,8 @@
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Folder Include="Serialization\Entities\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
@@ -28,9 +28,13 @@ using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities;
#if !PocketPC && !SILVERLIGHT
using System.Data.Objects.DataClasses;
#endif
namespace Newtonsoft.Json.Serialization
{
@@ -101,9 +105,29 @@ namespace Newtonsoft.Json.Serialization
}
}
#if !PocketPC && !SILVERLIGHT
// don't include EntityKey on entities objects... this is a bit hacky
if (typeof(EntityObject).IsAssignableFrom(objectType))
serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList();
#endif
return serializableMembers;
}
#if !PocketPC && !SILVERLIGHT
private bool ShouldSerializeEntityMember(MemberInfo memberInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
{
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>))
return false;
}
return true;
}
#endif
/// <summary>
/// Creates a <see cref="JsonObjectContract"/> for the given type.
/// </summary>
@@ -124,7 +148,18 @@ namespace Newtonsoft.Json.Serialization
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.UnderlyingType);
if (containerAttribute != null)
{
contract.IsReference = containerAttribute._isReference;
}
#if !PocketPC
else
{
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.UnderlyingType);
// doesn't have a null value
if (dataContractAttribute != null && dataContractAttribute.IsReference)
contract.IsReference = true;
}
#endif
#if !PocketPC && !SILVERLIGHT
foreach (MethodInfo method in contract.UnderlyingType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
@@ -88,7 +88,7 @@ namespace Newtonsoft.Json.Serialization
if (reader == null)
throw new ArgumentNullException("reader");
if (!reader.Read())
if (reader.TokenType == JsonToken.None && !reader.Read())
return null;
return CreateValue(reader, objectType, null, null);
@@ -230,32 +230,47 @@ namespace Newtonsoft.Json.Serialization
writer.WriteEndObject();
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract)
internal static bool TryConvertToString(object value, Type type, out string s)
{
contract.InvokeOnSerializing(value);
#if !SILVERLIGHT && !PocketPC
TypeConverter converter = TypeDescriptor.GetConverter(contract.UnderlyingType);
TypeConverter converter = TypeDescriptor.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null && !(converter is ComponentConverter) && (converter.GetType() != typeof (TypeConverter) || value is Type))
if (converter != null && !(converter is ComponentConverter) && (converter.GetType() != typeof(TypeConverter) || value is Type))
{
if (converter.CanConvertTo(typeof (string)))
if (converter.CanConvertTo(typeof(string)))
{
writer.WriteValue(converter.ConvertToInvariantString(value));
contract.InvokeOnSerialized(value);
return;
s = converter.ConvertToInvariantString(value);
return true;
}
}
#else
if (value is Guid || value is Type || value is Uri)
{
writer.WriteValue(value.ToString());
return;
s = value.ToString();
return true;
}
#endif
s = null;
return false;
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract)
{
contract.InvokeOnSerializing(value);
string s;
if (TryConvertToString(value, contract.UnderlyingType, out s))
{
writer.WriteValue(s);
#if !SILVERLIGHT && !PocketPC
contract.InvokeOnSerialized(value);
#endif
return;
}
SerializeStack.Add(value);
writer.WriteStartObject();