Yes, you can. I just did so with the following code.
[Serializable]
public struct TestStruct
{
public int Value1 { get; set; }
public int Value2 { get; set; }
public string Value3 { get; set; }
public double Value4 { get; set; }
}
TestStruct s1 = new TestStruct();
s1.Value1 = 43265;
s1.Value2 = 2346;
s1.Value3 = "SE";
string serialized = jss.Serialize(s1);
s2 = jss.Deserialize<TestStruct>(serialized);
Console.WriteLine(serialized);
Console.WriteLine(s2.Value1 + " " + s2.Value2 + " " + s2.Value3 + " " + s2.Value4);
What did it do? Exactly what it should have, serialized and deserialized the struct
.
Output:
{"Value1":43265,"Value2":2346,"Value3":"SE","Value4":5235.3}
43265 2346 SE 5235.3
Funny, that's the TestStruct
serialized and deserialized to/from JSON
.
What about a default constructor? All struct
objects have a default constructor, it's one of the fundamental properties of a struct
object, and that default constructor is merely responsible for clearing the memory required for a struct
object to the default values. Therefore, the serializer
already knows there is a default constructor, and therefore can proceed as if it's a regular object (which it is).
Notes:
This example uses System.Web.Script.Serialization.JavaScriptSerializer
.
This example assumes all the variables inside the struct
are properties. If they are not, then this answer may not work. It seems to work for me with fields
in place of the properties
, but that's not a best-practice. You should always make sure that the public
variables in all objects are properties
.