How to write your own POCO serializer / deserializer?

I would like to write my own .NET serializer / deserializer for FIX messages (which are not like XML). Basically the message is encoded as <tag>=<value>;<tag>=<value>;...

So an example could be:

 51=2;20=hello;31=2 

I would like to use my FIX Serializer class, similar to how I use the XMLSerializer class to serialize / deserialize messages. I would suggest that I would write a FIX message class, for example:

 [Serializable] public class FixMessage { [FIXValuePair(51)] public double Price { get; set; } [FIXValuePair(20)] public string SomethingElse { get; set; } } 

Any pointers on how I will write such a serializer / deserializer?

+6
source share
1 answer

Using reflection, you can cycle through the properties of the object you are serializing, then for each property you can check the attributes (using reflection again). And at the end, you send your output to the stream.

Your code might look something like this:

 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; } 
+6
source

All Articles