Using the class JavaScriptSerializer
the color is serialized, but when it comes to deserialize it cannot create the objects again, now using its own library to work with Json, the Color structure is built again. I have 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"
}
}
Performing
cores teste = serial.Deserialize<cores>(serializado);
Console.WriteLine(teste.corI + " - " + teste.corE);
Exit:
The JavaScriptSerializer
failed to build the object again
Color [Empty] - Color [Empty]
Newtonsoft.Json
Now using a class that works with Json, in case I used the Newtonsoft.Json library, the result is different:
string serializado = JsonConvert.SerializeObject(new cores() { corI = cor, corE = cor2 });
Console.Write(serializado);
Exit
Exit is much simpler
{"Cori":"255, 0, 0","core":"0, 0, 255"}
Performing
cores teste = JsonConvert.DeserializeObject<cores>(serializado);
Console.WriteLine(teste.corI + " - " + teste.corE);
Exit
He can reconstruct the object.
Color [Red] - Color [Blue]
Completion
I don’t know why you are using this class, but it seems to me not a good option, when you just want to turn an object into a string, I recommend you to use one of the Json libraries, which are optimized and suitable for this.
It would not be easier just to save the color in Hex or RGB format in your Json structure?
– gato
Also, I don’t know if it is possible to get the same results by creating a structure, since Color is a structure and not a class. Anyway, take a look here to see if it helps you.
– gato
@Cat I already fixed it, I’m passing an array of integers. But I asked the question because it got me kind of stuck and I wanted to know why it didn’t work.
– Francisco
Do you have any reason to use the
JavaScriptSerializer
to serialize for json?– Tiago S