11namespace Chickensoft . Serialization . Godot ;
22
33using System ;
4- using System . Globalization ;
54using System . Text . Json ;
65using System . Text . Json . Serialization ;
6+ using System . Text . RegularExpressions ;
77using global ::Godot ;
88
99/// <summary>Color JSON converter.</summary>
10- public class ColorConverter : JsonConverter < Color > {
10+ public partial class ColorConverter : JsonConverter < Color > {
11+ [ GeneratedRegex ( "\\ s*rgba\\ ((.*)\\ )\\ s*" , RegexOptions . IgnoreCase , "en-US" ) ]
12+ private static partial Regex RgbaRegex ( ) ;
13+
14+ [ GeneratedRegex ( "\\ s+" , RegexOptions . IgnoreCase , "en-US" ) ]
15+ private static partial Regex WhitespaceRegex ( ) ;
16+
17+ private static readonly Regex _rgbaRegex = RgbaRegex ( ) ;
18+ private static readonly Regex _whitespaceRegex = WhitespaceRegex ( ) ;
19+
1120 /// <inheritdoc />
1221 public override bool CanConvert ( Type typeToConvert ) =>
1322 typeToConvert == typeof ( Color ) ;
@@ -18,11 +27,14 @@ public override Color Read(
1827 Type typeToConvert ,
1928 JsonSerializerOptions options
2029 ) {
21- var rgba = ( uint ) 0x000000ff ;
30+ var r = 0f ;
31+ var g = 0f ;
32+ var b = 0f ;
33+ var a = 1f ;
2234
2335 while ( reader . Read ( ) ) {
2436 if ( reader . TokenType == JsonTokenType . EndObject ) {
25- return new Color ( rgba ) ;
37+ return new Color ( r , g , b , a ) ;
2638 }
2739
2840 if ( reader . TokenType != JsonTokenType . PropertyName ) {
@@ -34,7 +46,26 @@ JsonSerializerOptions options
3446
3547 switch ( propertyName ) {
3648 case "rgba" :
37- rgba = uint . Parse ( reader . GetString ( ) ?? string . Empty , NumberStyles . HexNumber ) ;
49+ var match = _rgbaRegex . Match ( reader . GetString ( ) ?? string . Empty ) ;
50+ if ( match . Groups [ 1 ] . Success ) {
51+ var values = _whitespaceRegex
52+ . Replace ( match . Groups [ 1 ] . Value , "" )
53+ . Split ( "," ) ;
54+
55+ if ( values . Length == 4 ) {
56+ r = float . Parse ( values [ 0 ] ) ;
57+ g = float . Parse ( values [ 1 ] ) ;
58+ b = float . Parse ( values [ 2 ] ) ;
59+ a = float . Parse ( values [ 3 ] ) ;
60+ }
61+ else {
62+ throw new JsonException ( "Unable to parse property 'rgba' of Color" ) ;
63+ }
64+ }
65+ else {
66+ throw new JsonException ( "Unable to parse property 'rgba' of Color" ) ;
67+ }
68+
3869 break ;
3970 default :
4071 break ;
@@ -51,7 +82,7 @@ public override void Write(
5182 JsonSerializerOptions options
5283 ) {
5384 writer . WriteStartObject ( ) ;
54- writer . WriteString ( "rgba" , value . ToRgba32 ( ) . ToString ( "X" ) ) ;
85+ writer . WriteString ( "rgba" , $ "rgba( { value . R } , { value . G } , { value . B } , { value . A } )" ) ;
5586 writer . WriteEndObject ( ) ;
5687 }
5788}
0 commit comments