How to Serialize List<T>?
I have Class A. Class B and Class C are part of Cla开发者_如何学运维ss A.
Class A
{
//Few Properties of Class A
List<typeof(B)> list1 = new List<typeof(B)>()
List<typeof(C)> list2 = new List<typeof(C)>()
Nsystem NotSystem { get; set; } // Enum Property Type
}
public enum Nsystem {
A = 0,
B = 1,
C = 2
}
I want to Serialize Class A and want to produce XML with it; I also want to serialize list1 and list2 and also the Enum...
What is a good approach to Serialize this XML because I need the functionality of converting an Object into XML and XML into an Object ...
What are some good options to do this? Thanks
You could use the XMLSerializer:
var aSerializer = new XmlSerializer(typeof(A));
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
aSerializer.Serialize(sw, new A()); // pass an instance of A
string xmlResult = sw.GetStringBuilder().ToString();
For this to work properly you will also want xml annotations on your types to make sure it is serialized with the right naming, i.e.:
public enum NSystem { A = 0, B = 1, C = 2 }
[Serializable]
[XmlRoot(ElementName = "A")]
Class A
{
//Few Properties of Class A
[XmlArrayItem("ListOfB")]
List<B> list1;
[XmlArrayItem("ListOfC")]
List<C> list2;
NSystem NotSystem { get; set; }
}
Edit:
Enum
properties are serialized by default with the name of the property as containing XML element and its enum value as XML value, i.e. if the property NotSystem
in your example has the value C
it would be serialized as
<NotSystem>C</NotSystem>
Of course you can always change the way the property is serialized by doing a proper annotation, i.e using [XmlAttribute]
so it's serialized as an attribute, or [XmlElement("Foobar")]
so it's serialized using Foobar
as element name. More extensive documentation is available on MSDN, check the link above.
Easiest way: to do BINARY serialization of any object (Images also and lot of other data!) with IO error catching.
To the class that we need to serialize we need to add [Serializable]
[Serializable]//this like
public class SomeItem
{}
Serialization wrapper:
public static class Serializator
{
private static BinaryFormatter _bin = new BinaryFormatter();
public static void Serialize(string pathOrFileName, object objToSerialise)
{
using (Stream stream = File.Open(pathOrFileName, FileMode.Create))
{
try
{
_bin.Serialize(stream, objToSerialise);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
}
}
public static T Deserialize<T>(string pathOrFileName)
{
T items;
using (Stream stream = File.Open(pathOrFileName, FileMode.Open))
{
try
{
items = (T) _bin.Deserialize(stream);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
}
return items;
}
}
and using of the solution:
List<SomeItem> itemsCollected; //list with some data
Serializator.Serialize("data.dat", itemsCollected); // trying to serialise
var a = Serializator.Deserialize<%dataType%>("%dataPath%");
var a = Serializator.Deserialize<List<SomeItem>>("data.dat");
// trying to DeSerialize;
// And important thing that you need to write here
// correct data format instead of List<SomeItem>
in case of error was occured, error will be written to the console.
public IList<Object> Deserialize(string a_fileName)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Object>));
TextReader reader = new StreamReader(a_fileName);
object obj = deserializer.Deserialize(reader);
reader.Close();
return (List<Object>)obj;
}
public void Serialization(IList<Object> a_stations,string a_fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Object>));
using (var stream = File.OpenWrite(a_fileName))
{
serializer.Serialize(stream, a_stations);
}
}
you can use this
[XmlArray("array_name")]
[XmlArrayItem("Item_in_array")]
public List<T> _List;
Do you need to use XML as the representation? You may want to consider binary representations as well, which are usually faster and more compact. You have the BinaryFormatter that comes built in, or even better you can use protocol buffers that is blazing fast and super compact. If you need XML you may want to think whether you want to support some kind of interoperability with other languages and technologies or even platforms. If it is only C# to c# both the XmlSerializer for Xml or the BinaryFormatter are fine. If you are going to interact with Javascript you may consider using JSON (You can try JSON.NET. Also, if you want to support Windows Phone or other more constrained devices you, it may just be easier to use the XmlSerializer that works anywhere.
Finally, you may prefer to just have a common infrastructure and support many serialization mechanisms and transports. Microsoft offers a wonderful (albeit a bit slow) solution in WCF. Perhaps if you say more about your system's requirements, it will be easier to suggest an implementation. The good thing is that you have plenty of options.
As cloudraven suggested, you could use binary representations. While looking for solutions I came upon this link. Basically, you mark your A class as [Serializable], and the same goes for your B and C classes. Then you might use functions such as these ones to Serialize and Deserialize
JAXB is the best I ever used.
http://www.oracle.com/technetwork/articles/javase/index-140168.html
From XML:
QuestionEntity obj = null;
try {
JAXBContext ctx = JAXBContext.newInstance(QuestionEntity.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
obj = (QuestionEntity) unmarshaller.unmarshal(new StreamSource(new StringReader(xml)));
} catch (JAXBException e) {
e.printStackTrace();
}
To XML:
JAXBContext ctx = JAXBContext.newInstance(TestEntity.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(this, stringWriter);
return stringWriter.toString();
精彩评论