Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom POCO serializer/deserializer?

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?

like image 335
Denis Avatar asked Jan 23 '13 21:01

Denis


1 Answers

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;
}
like image 143
Z.D. Avatar answered Oct 01 '22 03:10

Z.D.