在.NET中自定义对象的序列化

Akh*_*esh 7 .net serialization

我需要将对象列表序列化为平面文件.电话会是这样的:

class MyObject
{
    public int x;
    public int y;
    public string a;
    public string b;
}
Run Code Online (Sandbox Code Playgroud)

当我序列化这个对象时,应该在ascii编码的平面文件中写入一条记录.现在,字段x的长度应为10个字符(右对齐),字段y应为20个字符(右对齐),fiels a应为40(左对齐),字段b应为100个字符(左对齐).我怎样才能实现这样的目标.

序列化对象应如下所示:

        25                   8                                     akjsrj                                                                                          jug
Run Code Online (Sandbox Code Playgroud)

我想可能是我可以将自定义属性属性应用于字段,并可以在运行时决定如何序列化字段..

jga*_*fin 13

这是一个使用普通旧反射和自定义属性的解决方案.它只会为每个文件序列化/反序列化一个项目,但您可以轻松地为每个文件添加对多个项目的支持.

// Attribute making it possible
public class FlatFileAttribute : Attribute
{
    public int Position { get; set; }
    public int Length { get; set; }
    public Padding Padding { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="FlatFileAttribute"/> class.
    /// </summary>
    /// <param name="position">Each item needs to be ordered so that 
    /// serialization/deserilization works even if the properties 
    /// are reordered in the class.</param>
    /// <param name="length">Total width in the text file</param>
    /// <param name="padding">How to do the padding</param>
    public FlatFileAttribute(int position, int length, Padding padding)
    {
        Position = position;
        Length = length;
        Padding = padding;
    }
}

public enum Padding
{
    Left,
    Right
}


/// <summary>
/// Serializer making the actual work
/// </summary>
public class Serializer
{
    private static IEnumerable<PropertyInfo> GetProperties(Type type)
    {
        var attributeType = typeof(FlatFileAttribute);

        return type
            .GetProperties()
            .Where(prop => prop.GetCustomAttributes(attributeType, false).Any())
            .OrderBy(
                prop =>
                ((FlatFileAttribute)prop.GetCustomAttributes(attributeType, false).First()).
                    Position);
    }
    public static void Serialize(object obj, Stream target)
    {
        var properties = GetProperties(obj.GetType());

        using (var writer = new StreamWriter(target))
        {
            var attributeType = typeof(FlatFileAttribute);
            foreach (var propertyInfo in properties)
            {
                var value = propertyInfo.GetValue(obj, null).ToString();
                var attr = (FlatFileAttribute)propertyInfo.GetCustomAttributes(attributeType, false).First();
                value = attr.Padding == Padding.Left ? value.PadLeft(attr.Length) : value.PadRight(attr.Length);
                writer.Write(value);
            }
            writer.WriteLine();
        }
    }

    public static T Deserialize<T>(Stream source) where T : class, new()
    {
        var properties = GetProperties(typeof(T));
        var obj = new T();
        using (var reader = new StreamReader(source))
        {
            var attributeType = typeof(FlatFileAttribute);
            foreach (var propertyInfo in properties)
            {
                var attr = (FlatFileAttribute)propertyInfo.GetCustomAttributes(attributeType, false).First();
                var buffer = new char[attr.Length];
                reader.Read(buffer, 0, buffer.Length);
                var value = new string(buffer).Trim();

                if (propertyInfo.PropertyType != typeof(string))
                    propertyInfo.SetValue(obj, Convert.ChangeType(value, propertyInfo.PropertyType), null);
                else
                    propertyInfo.SetValue(obj, value.Trim(), null);
            }
        }
        return obj;
    }

}
Run Code Online (Sandbox Code Playgroud)

还有一个小演示:

// Sample class using the attributes
public class MyObject
{
    // First field in the file, total width of 5 chars, pad left
    [FlatFile(1, 5, Padding.Left)]
    public int Age { get; set; }

    // Second field in the file, total width of 40 chars, pad right
    [FlatFile(2, 40, Padding.Right)]
    public string Name { get; set; }
}

private static void Main(string[] args)
{
    // Serialize an object
    using (var stream = File.OpenWrite("C:\\temp.dat"))
    {
        var obj = new MyObject { Age = 10, Name = "Sven" };
        Serializer.Serialize(obj, stream);
    }

    // Deserialzie it from the file
    MyObject readFromFile = null;
    using (var stream = File.OpenRead("C:\\temp.dat"))
    {
        readFromFile = Serializer.Deserialize<MyObject>(stream);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 关于此代码的几点快速注释。您没有在反序列化中使用Position属性。同样,如果添加一些东西来检查属性的存在,则可以选择为类的每个属性提供一个属性。否则,这太棒了,真的帮助了我。 (2认同)

Dav*_*ead 5

是的,您可以通过添加自定义属性并创建自己的序列化器来实现这一点。

本文提供了创建自定义二进制序列化器的示例。

http://www.codeproject.com/KB/dotnet/CustomSerializationPart2.aspx

  • 在编辑问题之前,文件格式看起来确实是二进制的。请重新考虑您的否决票。 (4认同)

aKz*_*enT -1

这个格式是固定的吗?如果您对如何格式化输出有意见,我强烈建议使用protobuf-net。这是一个令人难以置信的快速库,它将使用二进制序列化方法来处理您的对象,并且开销最小,并且(我重复一遍)令人难以置信的性能。该协议是谷歌专门为了这些优点而发明的。

如果无法更改格式,可以创建自定义属性并在运行时读出它们。但请记住,反射可能会有点慢,具体取决于您的序列化需求。如果您只有一种类型的对象,也许最好提供一种特殊的序列化服务,将属性直接写入文件。

链接: http: //code.google.com/p/protobuf-net/