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.
- C#
- VB.NET
public class ColorJsonConverter : JsonConverter<Color>
Public Class ColorJsonConverter
Inherits JsonConverter(Of 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
ColorJsonConverter()
Initializes a new instance of ColorJsonConverter.
Methods
Read(reader, typeToConvert, options)
Reads a Color from a JSON string value.
| Parameter | Type | Description |
|---|---|---|
| reader | Utf8JsonReader | The reader positioned on the JSON string token. |
| typeToConvert | Type | The type to convert (Color). |
| options | JsonSerializerOptions | The 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);
Write(writer, value, options)
Writes a Color to JSON in RGBA format.
| Parameter | Type | Description |
|---|---|---|
| writer | Utf8JsonWriter | The writer to write the value to. |
| value | Color | The color to write. |
| options | JsonSerializerOptions | The 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)\""