title: Json.NET Serialization with Extra Properties; Preserving Serializer Settings
body: <p>I'd like to introduce some metadata properties into the json output for instances of a particular type when JSON.NET serializes the type.</p>
  
  <p>What is the best way to introduce these additional properties while preserving the serialization context and settings?</p>
  
  <hr>
  
  <p>I know that I can implement a <code>JsonConverter</code> and add it to the serializer settings.  Here's an example implementation of <code>WriteJson</code>:</p>
  
  <pre><code>public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
      var Json = JObject.FromObject(value, serializer);
  
      //modify Json by adding some properties ...
  
      Json.WriteTo(writer);
  }
  </code></pre>
  
  <p>However, this presents a few problems that I'm not sure how to get around:</p>
  
  <p>If the serializer is configured by setting: </p>
  
  <p><code>ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore</code></p>
  
  <p>then attempting to call <code>JObject.FromObject(value, serializer)</code> serializes nothing, since JSON.NET has already determined that the value is being serialized (and so it ignores further attempts at serializing the same reference).</p>
  
  <p>If I set <code>ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize</code> then I end up with an infinite recursion loop.  Calling <code>JObject.FromObject(value, serializer)</code> ends up re-entering <code>WriteJson</code> of my custom <code>JsonConverter</code>.</p>
  
  <p>If instead I create a new serializer, or call <code>JObject.FromObject(value)</code> (as shown in <a href="http://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm" rel="nofollow">this example</a>), I will no longer be using the same serializer settings.  While the output would have the extra properties, it may not match the rest of the serialized json if other converters, contract resolvers, etc. have been configured for the original serializer.  Additionally, I've lost the serialization context for reference loop handling, and so references that would have been skipped in the original output would no longer be skipped.</p>
  
  <p>Is there any better way to hook into the serialization process that permits you to modify the json produced by the original serializer?</p>
  
  <hr>
  
  <p>Update: For now I've implemented a less than desirable workaround which is to provide a settings factory <code>Func&lt;JsonSerializerSettings&gt;</code> to my custom <code>JsonConverter</code>. The provided settings have to exclude the converter to avoid the recursion loop and this doesn't preserve the serialization context. Additionally, any nested objects will not receive additional properties since the converter is no longer configured.</p>