Friday, July 21, 2017

Colorful serialization

I was writing some code to serialize a C# class to JSON and needed to export a System.Drawing.Color field as a hex string. Thankfully it's easy to customize the output using Json.NET. I created the following custom converter to save colors as hex strings (like #FFF0B6)

public class ColorHexConverter : JsonConverter {
 
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
  var color = (Color)value;
  var hexString = color.IsEmpty ? string.Empty : string.Concat("#", (color.ToArgb() & 0x00FFFFFF).ToString("X6");
  writer.WriteValue(hexString);
 }
 
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
  var hexString = reader.Value.ToString();
  if (hexString == null || !hexString.StartsWith("#")) return Color.Empty;
  return ColorTranslator.FromHtml(hexString);
 }
 
 public override bool CanConvert(Type objectType) {
  return objectType == typeof(Color);
 }
}

And example usage:

[JsonConverter(typeof(ColorHexConverter))]
public Color BackgroundColor;

3 comments:

Anonymous said...

Just as a word of warning - in the ReadJson function, you want to use reader.Value as string, rather than reader.ReadAsString() as this consumes the next token rather than viewing the current one.

Derek Antrican said...

Here to echo what "Anonymous" said - "reader.ReadAsString()" should instead be "reader.Value.ToString()"

Brad Patton said...

Updated the code. Thanks for those who pointed it out.