How to serialize a color with Json?

2

I have the following code, in which I am trying to serialize and deserialize a class that has 2 variables Color :

static void Main(string[] args)
{
    Color cor = Color.FromArgb(255, 255, 0, 0);
    Color cor2 = Color.FromArgb(255, 0, 0, 255);
    JavaScriptSerializer serial = new JavaScriptSerializer();
    string serializado = serial.Serialize(new cores() { corI=cor, corE=cor2 });
    cores teste = serial.Deserialize<cores>(serializado);
    Console.WriteLine(teste.corI + " - " + teste.corE);
}

class cores
{
    public Color corI { get; set; }
    public Color corE { get; set; }
}

However, the output of this program is:

Color [Empty] - Color [Empty]

That is, it did not work.

My question is, why Json does not work for Color? How to make it work?

    
asked by anonymous 20.08.2017 / 17:57

1 answer

1

Using the JavaScriptSerializer class, the color is serialized, however, at the time of deserialization it can not create objects again, now using its own library to work with Json, the Color structure is rebuilt. I made the comparisons below:

JavaScriptSerializer

JavaScriptSerializer serial = new JavaScriptSerializer();
string serializado = serial.Serialize(new cores() { corI=cor, corE=cor2 });
Console.Write(serializado);

Exit:

  

{ "corI":{ "R":255, "G":0, "B":0, "A":255, "IsKnownColor":false, "IsEmpty":false, "IsNamedColor":false, "IsSystemColor":false, "Name":"ffff0000" }, "corE":{ "R":0, "G":0, "B":255, "A":255, "IsKnownColor":false, "IsEmpty":false, "IsNamedColor":false, "IsSystemColor":false, "Name":"ff0000ff" } }

Deseralizing

cores teste = serial.Deserialize<cores>(serializado);
Console.WriteLine(teste.corI + " - " + teste.corE);

Exit:

JavaScriptSerializer could not construct object again

  

Color [Empty] - Color [Empty]

NewtonSoft.Json

Now using a class that works with Json, in the case I used the library NewtonSoft.Json, the result is different:

string serializado = JsonConvert.SerializeObject(new cores() { corI = cor, corE = cor2 });
Console.Write(serializado);

Exit

Output is much simpler

  

{"cori": "255, 0, 0", "corE": "0, 0, 255"}

Deseralizing

cores teste = JsonConvert.DeserializeObject<cores>(serializado);
Console.WriteLine(teste.corI + " - " + teste.corE);

Exit

It manages to rebuild the object.

  

Color [Red] - Color [Blue]

Conclusion

I do not know why you are using this class, but it does not seem like a good option, when you just want to turn an object into a string, I recommend you use one of Json's libraries, which are optimized for that.

    
20.08.2017 / 22:19