What is the easiest way to save an object in a file without serialization attributes?

I have different objects in C # that I would like to save to a file (preferably XML), but I cannot use serialization, since the class is not written by me, but from the DLL.

What is the best solution for this?

+5
source share
5 answers

I ended up using the JavaScriptSerializer, and it does exactly what I was looking for:

List<Person> persons = new List<Person>();
persons.Add(new Person(){Name = "aaa"});
persons.Add(new Person() { Name = "bbb" });

JavaScriptSerializer javaScriptSerializer  = new JavaScriptSerializer();
var strData = javaScriptSerializer.Serialize(persons);

var persons2 = javaScriptSerializer.Deserialize<List<Person>>(strData);
+3
source

I have hacked a quick extension method that will be "serialized" in XML, given an object that is not related to serialization. This is pretty crude and does not require a lot of validation and the generated XML, which you can easily customize to meet your needs:

public static string SerializeObject<T>(this T source, bool serializeNonPublic = false)
{
    if (source == null)
    {
        return null;
    }

    var bindingFlags = BindingFlags.Instance | BindingFlags.Public;

    if (serializeNonPublic)
    {
        bindingFlags |= BindingFlags.NonPublic;
    }

    var properties = typeof(T).GetProperties(bindingFlags).Where(property => property.CanRead).ToList();
    var sb = new StringBuilder();

    using (var writer = XmlWriter.Create(sb))
    {
        writer.WriteStartElement(typeof(T).Name);
        if (properties.Any())
        {
            foreach (var property in properties)
            {
                var value = property.GetValue(source, null);

                writer.WriteStartElement(property.Name);
                writer.WriteAttributeString("Type", property.PropertyType.Name);
                writer.WriteAttributeString("Value", value.ToString());
                writer.WriteEndElement();
            }
        }
        else if (typeof(T).IsValueType)
        {
            writer.WriteValue(source.ToString());
        }

        writer.WriteEndElement();
    }

    return sb.ToString();
}

I tested it in this class:

private sealed class Test
{
    private readonly string name;

    private readonly int age;

    public Test(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public string Name
    {
        get
        {
            return this.name;
        }
    }

    public int Age
    {
        get
        {
            return this.age;
        }
    }
}

3 object. XML :

<?xml version="1.0" encoding="utf-16"?>
<Test>
  <Name Type="String" Value="John Doe" />
  <Age Type="Int32" Value="35" />
</Test>

<?xml version="1.0" encoding="utf-16"?>
<Int32>3</Int32>

<?xml version="1.0" encoding="utf-16"?>
<Object />

.

+1

DLL.

EDIT: AutoMapper , , , , , , . - , - , ( ), , AutoMapper - , , .

0

POCO ( ), DLL. , , ,.NET 3.5 LINQ. Linq .

, , , . , DLL, , . , .

using System;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Xml.Linq;

namespace ExampleSerializer
{
    class Program
    {
        // example class to serialize
        [Serializable]
        public class SQLBit
        {
            [XmlElement("Name")]
            public string Name { get; set; }

            [XmlText]
            public string data { get; set; }
        }

        // example class to populate to get test data
        public class example
        {
            public string Name { get; set; }
            public string data { get; set; }
        }

        static void Main(string[] args)
        {
            string s = "";

            // make a generic and put some data in it from the test
            var ls = new List<example> { new example { Name = "thing", data = "data" }, new example { Name = "thing2", data = "data2" } };

            // make a second generic and put data from the first one in using a lambda
            // statement creation method.  If your object returned from DLL is a of a
            // type that implements IEnumerable it should be able to be used.
            var otherlist = ls.Select(n => new SQLBit
                {
                    Name = n.Name,
                    data = n.data
                });

            // start a new xml serialization with a type.
            XmlSerializer xmler = new XmlSerializer(typeof(List<SQLBit>));

            // I use a textwriter to start a new instance of a stream writer
            TextWriter twrtr = new StreamWriter(@"C:\Test\Filename.xml");

            // Serialize the stream to the location with the list
            xmler.Serialize(twrtr, otherlist);

            // Close
            twrtr.Close();

            // TODO: You may want to put this in a try catch wrapper and make up your 
            // own classes.  This is a simple example.
         }
    }
}
0

, " " .

If I understand correctly, you want to serialize objects that do not have serialization attributes.

There are libraries like sharpserializer and protobuf-net that can do the job for you.

0
source

All Articles