Skip to main content

ColorJsonConverter

Namespace: Wisej.Web.Ext.ChartJS4.Serialization

Assembly: Wisej.Web.Ext.ChartJS4 (4.1.0.0)

JSON converter for Color objects. Converts colors to RGBA format for Chart.js.

public class ColorJsonConverter : JsonConverter<Color>

Colors are written as "rgba(r, g, b, a)" strings, with the alpha channel expressed as a value between 0 and 1 formatted with two decimals using the invariant culture. Empty and fully transparent colors are written as null. When reading, both the rgba(…) format and any HTML color (e.g. "#FF0000" or "red") are accepted.

Example:

var options = new JsonSerializerOptions();
options.Converters.Add(new ColorJsonConverter());
var json = JsonSerializer.Serialize(Color.FromArgb(128, 255, 0, 0), options);
// json == "\"rgba(255, 0, 0, 0.50)\""

Constructors​

Instance member ColorJsonConverter()​

Initializes a new instance of ColorJsonConverter.

Methods​

Instance member Read(reader, typeToConvert, options)​

Reads a Color from a JSON string value.

ParameterTypeDescription
reader by referenceUtf8JsonReaderThe reader positioned on the JSON string token.
typeToConvertTypeThe type to convert (Color).
optionsJsonSerializerOptionsThe serializer options in use.

Returns: Color. The parsed Color, or Empty if the value is null or empty.

Values in the rgba(r, g, b, a) format are parsed directly (the alpha value is scaled from 0–1 to 0–255); any other value is parsed with FromHtml.

Example:

var options = new JsonSerializerOptions();
options.Converters.Add(new ColorJsonConverter());
var color = JsonSerializer.Deserialize<Color>("\"rgba(0, 128, 255, 1)\"", options);

Instance member Write(writer, value, options)​

Writes a Color to JSON in RGBA format.

ParameterTypeDescription
writerUtf8JsonWriterThe writer to write the value to.
valueColorThe color to write.
optionsJsonSerializerOptionsThe serializer options in use.

Writes a string in the rgba(r, g, b, a) format, with the alpha channel as a 0–1 value with two decimals formatted using the invariant culture. Empty and colors with an alpha of 0 are written as null.

Example:

var options = new JsonSerializerOptions();
options.Converters.Add(new ColorJsonConverter());
var json = JsonSerializer.Serialize(Color.SteelBlue, options);
// json == "\"rgba(70, 130, 180, 1.00)\""