How to write a custom POCO serializer/deserializer?

与世无争的帅哥 提交于 2019-12-08 19:36:28

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/14489799/how-to-write-a-custom-poco-serializer-deserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!