title: Is there a better way to handle Encoding values with Json.Net?
body: <p>I am serializing/deserializing a class that has a property of type System.Text.Encoding with Json.Net. Trying out a simple test, my class serialized without any issue:</p>
  
  <pre><code>public class TestClass {
      public Encoding TheEncoding { get; set; }
  }
  
  var testClass = new TestClass { TheEncoding = Encoding.UTF8 };
  var json = JsonConvert.SerializeObject( testClass, Formatting.Indented );
  var obj = JsonConvert.DeserializeObject&lt;TestClass&gt;( json );
  </code></pre>
  
  <p>Serializes to:</p>
  
  <pre><code>{
    "TheEncoding": {
      "BodyName": "utf-8",
      "EncodingName": "Unicode (UTF-8)",
      "HeaderName": "utf-8",
      "WebName": "utf-8",
      "WindowsCodePage": 1200,
      "IsBrowserDisplay": true,
      "IsBrowserSave": true,
      "IsMailNewsDisplay": true,
      "IsMailNewsSave": true,
      "IsSingleByte": false,
      "EncoderFallback": {
        "DefaultString": "?",
        "MaxCharCount": 1
      },
      "DecoderFallback": {
        "DefaultString": "?",
        "MaxCharCount": 1
      },
      "IsReadOnly": true,
      "CodePage": 65001
    }
  }
  </code></pre>
  
  <p>However, when deserializing, I got an exception: </p>
  
  <blockquote>
    <p>Could not create an instance of type System.Text.Encoding. Type is an
    interface or abstract class and cannot be instantiated. Path
    'TheEncoding.BodyName', line 3, position 16.</p>
  </blockquote>
  
  <p>I was able to get past this issue by creating a custom converter that handles the System.Text.Encoding type:</p>
  
  <pre><code>public class JsonEncodingConverter : JsonConverter {
      public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) {
          // Serialize as the BodyName.
          serializer.Serialize( writer, ( value as Encoding ).BodyName );
      }
  
      public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) {
          // Already good to go.
          return existingValue;
      }
  
      public override bool CanConvert( Type objectType ) {
          return ( typeof ( Encoding ).IsAssignableFrom( objectType ) );
      }
  }
  
  var testClass = new TestClass { TheEncoding = Encoding.UTF8 };
  var json = JsonConvert.SerializeObject( testClass, Formatting.Indented, new JsonEncodingConverter() );
  var obj = JsonConvert.DeserializeObject&lt;TestClass&gt;( json , new JsonEncodingConverter() );
  </code></pre>
  
  <p>Serializing with the custom converter now produces:</p>
  
  <pre><code>{
    "TheEncoding": "utf-8"
  }
  </code></pre>
  
  <p>And this JSON can be successfully round-tripped back to the original object when deserialized with the custom converter.</p>
  
  <p>I'm new to Json.Net, and I have a strong feeling that I'm doing this the hard way! Surely there is a better and less involved way to handle System.Text.Encoding?</p>