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:
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<TestClass>( json );
Serializes to:
{
"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
}
}
However, when deserializing, I got an exception:
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.
I was able to get past this issue by creating a custom converter that handles the System.Text.Encoding type:
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<TestClass>( json , new JsonEncodingConverter() );
Serializing with the custom converter now produces:
{
"TheEncoding": "utf-8"
}
And this JSON can be successfully round-tripped back to the original object when deserialized with the custom converter.
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?