I would like to write a custom .NET serializer/deserializer for FIX messages (which aren't like XML). Basically the message is coded as <tag>=<value>;<tag>=<value>;...
So a sample one might be:
51=2;20=hello;31=2
I would like to use my FIX Serializer class similar to the way I use the XMLSerializer class to be able to serialize/deserialize messages. I would imagine I would write a FIX message class like:
[Serializable]
public class FixMessage
{
[FIXValuePair(51)]
public double Price { get; set; }
[FIXValuePair(20)]
public string SomethingElse { get; set; }
}
Any pointers on how I would write such a Serializer/Deserializer?
Using reflection you can loop thru the properties of the object you are serializing, then for each property you can check for attributes (again using reflection). And in the end you send your output to a stream.
Your code could look something like this (simplified):
public string Serialize(object o)
{
string result = ""; // TODO: use string builder
Type type = o.GeyType();
foreach (var pi in type.GetProperties())
{
string name = pi.Name;
string value = pi.GetValue(o, null).ToString();
object[] attrs = pi.GetCustomAttributes(true);
foreach (var attr in attrs)
{
var vp = attr as FIXValuePairAttribute;
if (vp != null) name = vp.Name;
}
result += name + "=" + value + ";";
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With