title: How do I make JSON.NET ignore object relationships?
body: <p>I'm working on an <a href="http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework" rel="noreferrer">Entity Framework</a> project. I want to serialize a bunch of entity class instances. I've bound these together into a container class:</p>
  
  <pre><code>public class Pseudocontext
  {
      public List&lt;Widget&gt; widgets;
      public List&lt;Thing&gt; things;
  </code></pre>
  
  <p>Etcetera... it is an instance of this class that I'm attempting to serialize. I want JSON.NET to serialize the members of each entity class instance that are actually columns in the underlying database. I do not want it to even attempt to serialize object references.</p>
  
  <p>In particular, my entity classes have virtual members that allow me to write C# code that navigates all my inter-entity relationships without worrying about actual key values, joins, etc., and I want JSON.NET to ignore the associated parts of my entity classes.</p>
  
  <p>On the surface, there seems to be a JSON.NET configuration option that does exactly what I'm talking about:</p>
  
  <pre><code>JsonSerializer serializer = new JsonSerializer();
  serializer.PreserveReferencesHandling = PreserveReferencesHandling.None;
  </code></pre>
  
  <p>Unfortunately, JSON.NET seems to be ignoring the second statement above.</p>
  
  <p>I actually found a web page (<a href="http://json.codeplex.com/workitem/24608" rel="noreferrer">http://json.codeplex.com/workitem/24608</a>) where someone else brought the same issue to the attention of James Newton-King himself, and his response (in its entirety) was "Write a custom contract resolver."</p>
  
  <p>As inadequate as I find that response to be, I have been attempting to follow its guidance. I would very much like to be able to write a "contract resolver" that ignored everything except primitive types, strings, DateTime objects, and my own Pseudocontext class along with the Lists it contains directly. If someone has an example of something that at least resembles that, it might be all I need. This is what I came up with on my own:</p>
  
  <pre><code>public class WhatDecadeIsItAgain : DefaultContractResolver
  {
      protected override JsonContract CreateContract(Type objectType)
      {
          JsonContract contract = base.CreateContract(objectType);
          if (objectType.IsPrimitive || objectType == typeof(DateTime) || objectType == typeof(string)
              || objectType == typeof(Pseudocontext) || objectType.Name.Contains("List"))
          {
              contract.Converter = base.CreateContract(objectType).Converter;
          }
          else
          {
              contract.Converter = myDefaultConverter;
          }
          return contract;
      }
      private static GeeThisSureTakesALotOfClassesConverter myDefaultConverter = new GeeThisSureTakesALotOfClassesConverter();
  }
  
  public class GeeThisSureTakesALotOfClassesConverter : Newtonsoft.Json.Converters.CustomCreationConverter&lt;object&gt;
  {
      public override object Create(Type objectType)
      {
          return null;
      }
  }
  </code></pre>
  
  <p>When I attempt to use the above (by setting serializer.ContractResolver to an instance of WhatDecadeIsItAgain prior to serialization), I get OutOfMemory errors during serialization that indicate that JSON.NET is encountering reference loops that never terminate (in spite of my efforts to make JSON.NET <strong><em>just ignore object references</em></strong>).</p>
  
  <p>I feel like my "custom contract resolver" may be wrong. As shown above, it's built around the premise that I should return the default "contract" for the types I do want to serialize, and a "contract" that simply returns "null" for all other types.</p>
  
  <p>I have no idea how correct these assumptions are, though, and it's not easy to tell. The JSON.NET design is very much based on implementation inheritance, method overriding, etc.; I'm not much of an <a href="http://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">OOP</a> guy, and I find that sort of design to be pretty obscure. Were there a "custom contract resolver" interface that I could implement, <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2012" rel="noreferrer">Visual Studio 2012</a> would be able to stub out the required methods very quickly, and I imagine I'd have little trouble filling the stubs in with real logic.</p>
  
  <p>I'd have no problem writing, for example, a method that returns "true" if I want to serialize an object of a supplied type and "false" otherwise. Perhaps I'm missing something, but I've found no such method to override, nor have I been able to find the hypothetical interface (ICustomContractResolver ?) that would tell me what I'm actually supposed to be doing in the last code snippet inserted above.</p>
  
  <p>Also, I realize that there are JSON.NET attributes ([JsonIgnore]?) that are designed to deal with situations like this. I can't really use that approach, since I'm using "model first". Unless I decide to tear up my entire project architecture, my entity classes will be automatically generated, and they will not contain JsonIgnore attributes, nor do I feel comfortable editing the automated classes to contain these attributes.</p>
  
  <p>Incidentally, for a while I <em>did</em> have things set up to serialize object references, and I was just ignoring all the superfluous "$ref" and "$id" data that JSON.NET was returning in its serialization output. I've abandoned that approach for the moment at least, because (rather suddenly) serialization started taking an inordinate amount of time (~45 minutes to get ~5&nbsp;MB of JSON).</p>
  
  <p>I haven't been able to tie that sudden change in performance back to anything specific that I did. If anything, the volume of data in my database is lower now than it was when serialization was actually completing in reasonable time. But I'd be more than happy with a return to the <em>status quo ante</em> (in which I was just having to ignore "$ref", "$id", etc.) if that could be achieved.</p>
  
  <p>At this point, I'm also open to the prospect of using some other JSON library, or a different strategy altogether. I feel like I could just use StringBuilder, System.Reflection, etc. and come of with my own, homemade solution... but isn't JSON.NET supposed to be able to handle this sort of thing pretty easily??</p>