title: Serialize Dynamic Property Name for an Object using JSON.NET
body: <p>I'm using JSON.NET for serialization of my objects for connecting to a REST API.  One of the properties in my object that needs to be serialized to JSON has a dynamic property name.
  If the value contained in the struct for this property is a numeric value, then the JSON property is "type_id", however if this value is a string value, then the JSON property name is "type_code".  I attempted to use a custom <code>JsonConverter</code> for this, but I get a <code>JsonWriterException</code> with this message when I attempt to serialize:</p>
  
  <blockquote>
    <p>"Token PropertyName in state Property would result in an invalid JSON object. Path ''."</p>
  </blockquote>
  
  <p>Below is a subset of my object, as seen below I didn't specify a property name in my object for that as such:</p>
  
  <pre><code>[JsonProperty("title",Required=Required.Always,Order=1)]
  public string Title { get; set; }
  
  [JsonProperty("date",Order=3)]
  [JsonConverter(typeof(IsoDateTimeConverter))]
  public DateTime Date { get; set; }
  
  [JsonProperty(Order=2)]
  [JsonConverter(typeof(TypeIdentifierJsonConverter))]
  public TypeIdentifier DocTypeIdentifier { get; set; }
  </code></pre>
  
  <p>In the TypeIdentifier class I have the following in my WriteJson() method:</p>
  
  <pre><code>public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
      TypeIdentifier docTypeId;
      id= (TypeIdentifier) value;
  
      writer.WritePropertyName(id.ParameterName);
      writer.WriteValue(id.Value);           
  }
  </code></pre>
  
  <p>However, I am assuming it's defaulting to the name of the object's property instead of my custom one, causing two property names for a single value within the JSON string.  How can the property name be set dynamically for this, since the JsonPropertyAttribute tag appears to pull the object's property name when not specified explicitly?</p>
  
  <p>NOTE:  This object will never need to be deserialized from this app.</p>
  
  <p><strong>EDIT:</strong>  This object is tagged with the <code>[JsonObject(MemberSerialization.OptIn)]</code> attribute</p>