WPF: SolidColorBrush Converter for System.Text.Json


I thought I would share a useful converter I wrote for my MUD client to serialize/deserialize a WPF SolidColorBrush using System.Text.Json.

The only note is that I hard coded the default color as beige if a color doesn't exist (that fit my needs but might need to be updated to fit yours).

/*
 * Avalon Mud Client
 *
 * @project lead      : Blake Pell
 * @website           : http://www.blakepell.com
 * @copyright         : Copyright (c), 2022 All rights reserved.
 * @license           : MIT
 */

using System.Text.Json;

namespace Avalon.Common
{
    /// <summary>
    /// <see cref="JsonConverter"/> for a WPF <see cref="SolidColorBrush"/>.
    /// </summary>
    public class SolidColorBrushConverter : JsonConverter<SolidColorBrush>
    {
        public override SolidColorBrush Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var hexValue = reader.GetString();

            if (string.IsNullOrWhiteSpace(hexValue))
            {
                return Brushes.Beige;
            }

            return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexValue) ?? Brushes.Beige);
        }

        public override void Write(Utf8JsonWriter writer, SolidColorBrush? value, JsonSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteStringValue(Brushes.Beige.Color.ToString());
                return;
            }

            writer.WriteStringValue(value.Color.ToString());
        }
    }
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.