I can serialize a list really easy:
List<String> fieldsToNotCopy =new List<String> {"Iteration Path","Iteration ID"};
fieldsToNotCopy.SerializeObject("FieldsToNotMove.xml");
Now I need a method like this:
List<String> loadedList = new List<String();
loadedList.DeserializeObject("FieldsToNotMove.xml");
Is there such a method? Or am I going to need to create an XML reader and load it in that way?
EDIT: Turns out there is no built in SerialzeObject. I had made one earlier in my project and forgot about it. When I found it I thought it was built in. In case you are curious this is the SerializeObject that I made:
// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
TextWriter textWriter = new StreamWriter(filename);
xmlSerializer.Serialize(textWriter, toSerialize);
textWriter.Close();
}
There is no such builtin method as SerializeObject but it's not terribly difficult to code one up.
public void SerializeObject(this List<string> list, string fileName) {
var serializer = new XmlSerializer(typeof(List<string>));
using ( var stream = File.OpenWrite(fileName)) {
serializer.Serialize(stream, list);
}
}
And Deserialize
public void Deserialize(this List<string> list, string fileName) {
var serializer = new XmlSerializer(typeof(List<string>));
using ( var stream = File.OpenRead(fileName) ){
var other = (List<string>)(serializer.Deserialize(stream));
list.Clear();
list.AddRange(other);
}
}
These are my serialize/deserialize extension methods that work quite well
public static class SerializationExtensions
{
public static XElement Serialize(this object source)
{
try
{
var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
var xdoc = new XDocument();
using (var writer = xdoc.CreateWriter())
{
serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
}
return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
}
catch (Exception x)
{
return new XElement("Error", x.ToString());
}
}
public static T Deserialize<T>(this XElement source) where T : class
{
try
{
var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T));
return (T)serializer.Deserialize(source.CreateReader());
}
catch //(Exception x)
{
return null;
}
}
}
public static class XmlSerializerFactory
{
private static Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();
public static XmlSerializer GetSerializerFor(Type typeOfT)
{
if (!serializers.ContainsKey(typeOfT))
{
System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));
var newSerializer = new XmlSerializer(typeOfT);
serializers.Add(typeOfT, newSerializer);
}
return serializers[typeOfT];
}
}
You just need to define a type for your list and use it instead
public class StringList : List<String> { }
Oh, and you don't NEED the XmlSerializerFactory, it's just there since creating a serializer is slow, and if you use the same one over and over this speeds up your app.
I'm not sure whether this will help you but I have dome something which I believe to be similar to you.
//A list that holds my data
private List<Location> locationCollection = new List<Location>();
public bool Load()
{
//For debug purposes
Console.WriteLine("Loading Data");
XmlSerializer serializer = new XmlSerializer(typeof(List<Location>));
FileStream fs = new FileStream("CurrencyData.xml", FileMode.Open);
locationCollection = (List<Location>)serializer.Deserialize(fs);
fs.Close();
Console.WriteLine("Data Loaded");
return true;
}
This allows me to deserialise all my data back into a List<> but i'd advise putting it in a try - catch block for safety. In fact just looking at this now is going to make me rewrite this in a "using" block too.
I hope this helps.
EDIT:
Apologies, just noticed you're trying to do it a different way but i'll leave my answer there anyway.
I was getting error while deserializing to object. The error was "There is an error in XML document (0, 0)". I have modified the Deserialize function originally written by #JaredPar to resolve this error. It may be useful to someone:
public static void Deserialize(this List<string> list, string fileName)
{
XmlRootAttribute xmlRoot = new XmlRootAttribute();
xmlRoot.ElementName = "YourRootElementName";
xmlRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(List<string>), xmlRoot);
using (var stream = File.OpenRead(fileName))
{
var other = (List<string>)(serializer.Deserialize(stream));
list.Clear();
list.AddRange(other);
}
}
Create a list of products be serialized
List<string> Products = new List<string>
{
new string("Product 1"),
new string("Product 2"),
new string("Product 3"),
new string("Product 4")
};
Serialization
using (FileStream fs = new FileStream(#"C:\products.txt", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, Products);
}
Deserialization
using (FileStream fs = new FileStream(#"C:\products.txt", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
var productList = (List<string>)bf.Deserialize(fs);
}
Related
When using XML serialization in C#, I use code like this:
public MyObject LoadData()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject));
using (TextReader reader = new StreamReader(settingsFileName))
{
return (MyObject)xmlSerializer.Deserialize(reader);
}
}
(and similar code for deserialization).
It requires casting and is not really nice. Is there a way, directly in .NET Framework, to use generics with serialization? That is to say to write something like:
public MyObject LoadData()
{
// Generics here.
XmlSerializer<MyObject> xmlSerializer = new XmlSerializer();
using (TextReader reader = new StreamReader(settingsFileName))
{
// No casts nevermore.
return xmlSerializer.Deserialize(reader);
}
}
An addition to #Oded, you can make the method Generic aswell:
public T ConvertXml<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));
}
This way you don't need to make the whole class generic and you can use it like this:
var result = ConvertXml<MyObject>(source);
Make your serialization class/method generic:
public T LoadData<T>()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(settingsFileName))
{
return (T)xmlSerializer.Deserialize(reader);
}
}
A simple generic wrapper:
public class GenericSerializer<T> : XmlSerializer
{
public GenericSerializer(): base(typeof(T)) { }
}
This will serialize your object to the bin/debug folder:
static void Main(string[] args)
{
Person p = new Person { Name = "HelloWorld" };
GenericSerializer<Person> ser = new GenericSerializer<Person>();
ser.Serialize(new StreamWriter("person.xml"), p);
}
Try this.
public class SerializeConfig<T> where T : class
{
public static void Serialize(string path, T type)
{
var serializer = new XmlSerializer(type.GetType());
using (var writer = new FileStream(path, FileMode.Create))
{
serializer.Serialize(writer, type);
}
}
public static T DeSerialize(string path)
{
T type;
var serializer = new XmlSerializer(typeof(T));
using (var reader = XmlReader.Create(path))
{
type = serializer.Deserialize(reader) as T;
}
return type;
}
}
always work's for me
public static string ObjectToXmlSerialize<T>(T dataToSerialize)
{
try
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
catch (Exception ex)
{
}
return null;
}
and this is for Deserialize:
public static T XmlDeserializeToObject<T>(string xmlText)
{
try
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
catch (Exception ex)
{
}
return default(T);
}
Currently I try to write a generic XML parser and having trouble to write a generic Parser Class.
My current Parser:
public class XmlFileLoader
{
public T GetDeserializedData<T>(Type targetType, string rootElementName, string filename)
where T: class
{
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(GetPath(filename));
reader.Read();
doc.Load(reader);
T result = DatabaseXmlSerializer.DeserializeXmlString<T>(doc.InnerXml, rootElementName, targetType);
return result;
}
}
My Deserializer:
public static class DatabaseXmlSerializer
{
public static T DeserializeXmlString<T>(string XmlString, string RootElementName , Type TargetType)
{
T tempObject = default;
using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(XmlString)))
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = RootElementName;
xRoot.IsNullable = true;
XmlSerializer xs = new XmlSerializer(TargetType, xRoot);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
tempObject = (T)xs.Deserialize(memoryStream);
}
return tempObject;
}
}
My call:
var loader= new XmlFileLoader();
var books = loader.GetDeserializedData<List<MySolution.Book>>(typeof(List<MySolution.Book>), "Bookstore", "Books.xml");
What is my concern?
I have to pass the type twice, but somehow i can't figure out how to just write it with one type.
I want my call to be like this:
var loader= new XmlFileLoader();
var books = loader.GetDeserializedData<List<MySolution.Book>>("Bookstore", "Books.xml");
There are so many errors in your code that I don't know what to do.
It's easier to rewrite the code completely.
public class XmlFileLoader
{
public T GetData<T>(string rootElementName, string filename)
{
var xmlSerializer = new XmlSerializer(typeof(T),
new XmlRootAttribute(rootElementName));
using (var xmlReader = XmlReader.Create(filename))
return (T)xmlSerializer.Deserialize(xmlReader);
}
}
This is the whole code!
Use it:
var xmlFileLoader = new XmlFileLoader();
var someModel = xmlFileLoader.GetData<SomeModel>("root", "filename");
The deserialization code is so simple that you can just throw out this class and just use XmlSerializer directly where you need it.
However, there is a serious problem when using XmlRootAttribute: multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. See documentation: Dynamically Generated Assemblies.
Therefore, it makes sense to cache serializer instances inside our class. Then its presence becomes justified.
public class XmlFileLoader
{
private static readonly Dictionary<(Type, string), XmlSerializer> serializers
= new Dictionary<(Type, string), XmlSerializer>();
public T GetData<T>(string rootElementName, string filename)
{
var key = (typeof(T), rootElementName);
if (!serializers.TryGetValue(key, out XmlSerializer xmlSerializer))
{
xmlSerializer = new XmlSerializer(typeof(T),
new XmlRootAttribute(rootElementName));
serializers.Add(key, xmlSerializer);
}
using (var xmlReader = XmlReader.Create(filename))
return (T)xmlSerializer.Deserialize(xmlReader);
}
}
I'm running into an issue where my JSON serializer is failing randomly due to the character < showing up from time to time. I can't nail down where this is coming from and I want to - on exception - reserialize using a different method so I can see a full representation of the offending object. Is there any way to do this?
My current code:
// data is of type 'object'
serialized = JsonConvert.SerializeObject(data, new JsonSerializerSettings() {
Error = delegate(object sender, ErrorEventArgs args) {
// reserialize here and output object so I know what the heck is going on
}
})
There is no foolproof way to serialize any and every possible c# object.
Instead, you have a few ways to attack your problem:
Turn on Json.NET tracing. See Debugging with Serialization Tracing. This should tell you where in your object graph the problem is occurring.
Rather than serializing with JsonConvert.SerializeObject(), if you serialize with JsonSerializer.Serialize() and write to a string using a JsonTextWriter wrapping a StringWriter, you can flush the writer and log the partial serialization. That may give some idea where the problem arises.
You can try serializing using various other serializers, and if any work, log the result.
If one of your object properties is throwing an exception, you might try to force serialization of fields instead. See JSON.Net: Force serialization of all private fields and all fields in sub-classes.
For instance, putting #1, #2 and #3 together gives the following method:
public static class JsonSerializerExtensions
{
public static string SerializeObject(object obj, JsonSerializerSettings settings = null)
{
settings = settings ?? new JsonSerializerSettings();
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
using (var jsonWriter = new JsonTextWriter(writer))
{
var oldError = settings.Error;
var oldTraceWriter = settings.TraceWriter;
var oldFormatting = settings.Formatting;
try
{
settings.Formatting = Newtonsoft.Json.Formatting.Indented;
if (settings.TraceWriter == null)
settings.TraceWriter = new MemoryTraceWriter();
settings.Error = oldError + delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
jsonWriter.Flush();
var logSb = new StringBuilder();
logSb.AppendLine("Serialization error: ");
logSb.Append("Path: ").Append(args.ErrorContext.Path).AppendLine();
logSb.Append("Member: ").Append(args.ErrorContext.Member).AppendLine();
logSb.Append("OriginalObject: ").Append(args.ErrorContext.OriginalObject).AppendLine();
logSb.AppendLine("Error: ").Append(args.ErrorContext.Error).AppendLine();
logSb.AppendLine("Partial serialization results: ").Append(sb).AppendLine();
logSb.AppendLine("TraceWriter contents: ").Append(settings.TraceWriter).AppendLine();
logSb.AppendLine("JavaScriptSerializer serialization: ");
try
{
logSb.AppendLine(new JavaScriptSerializer().Serialize(obj));
}
catch (Exception ex)
{
logSb.AppendLine("Failed, error: ").AppendLine(ex.ToString());
}
logSb.AppendLine("XmlSerializer serialization: ");
try
{
logSb.AppendLine(obj.GetXml());
}
catch (Exception ex)
{
logSb.AppendLine("Failed, error: ").AppendLine(ex.ToString());
}
logSb.AppendLine("BinaryFormatter serialization: ");
try
{
logSb.AppendLine(BinaryFormatterExtensions.ToBase64String(obj));
}
catch (Exception ex)
{
logSb.AppendLine("Failed, error: ").AppendLine(ex.ToString());
}
Debug.WriteLine(logSb);
};
var serializer = JsonSerializer.CreateDefault(settings);
serializer.Serialize(jsonWriter, obj);
}
finally
{
settings.Error = oldError;
settings.TraceWriter = oldTraceWriter;
settings.Formatting = oldFormatting;
}
}
return sb.ToString();
}
}
public static class XmlSerializerExtensions
{
public static T LoadFromXML<T>(this string xmlString)
{
using (StringReader reader = new StringReader(xmlString))
{
return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
}
public static string GetXml<T>(this T obj)
{
using (var textWriter = new StringWriter())
{
var settings = new XmlWriterSettings() { Indent = true, IndentChars = " " };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj);
return textWriter.ToString();
}
}
}
public static class BinaryFormatterExtensions
{
public static string ToBase64String<T>(T obj)
{
using (var stream = new MemoryStream())
{
new BinaryFormatter().Serialize(stream, obj);
return Convert.ToBase64String(stream.GetBuffer(), 0, checked((int)stream.Length)); // Throw an exception on overflow.
}
}
public static T FromBase64String<T>(string data)
{
return FromBase64String<T>(data, null);
}
public static T FromBase64String<T>(string data, BinaryFormatter formatter)
{
using (var stream = new MemoryStream(Convert.FromBase64String(data)))
{
formatter = (formatter ?? new BinaryFormatter());
var obj = formatter.Deserialize(stream);
if (obj is T)
return (T)obj;
return default(T);
}
}
}
You would likely replace the final Debug.WriteLine() with an appropriate logging method, then replace JsonConvert.SerializeObject(data) with JsonSerializerExtensions.SerializeObject(data) in your applications code.
I would like to create a method that Deserializes a serialized class.
Codes:
Settings newSettings = new Settings(); //Settings is a class.
Settings lastSettings = new Settings();
private void LoadXML(Type type,string filepath)
{
XmlSerializer serializer = new XmlSerializer(type);
FileStream fs = File.Open(filepath,FileMode.Open);
Settings newset = (Settings)serializer.Deserialize(fs); //Deserializes a serializable class file.
newSettings = newset; //Sets these settings as NewSettings
lastSettings = newSettingsXML; //Before form opening, sets information into form.
fs.Close();
}
Now i want to do these with a method. I created also different method for "Person" Class. This method reads person from xml file and sets these person into the form.
private void PersonFromXML(string filepath)
{
XmlSerializer serializer = new XmlSerializer(typeof(BindingList<Person>));
FileStream fs = File.Open(filepath,FileMode.Open);
BindingList<Person> XML_Person = (BindingList<Person>)serializer.Deserialize(fs);
NEW_XML_Person = XML_Person; // These are BindingList<Person>.
fs.Close();
Grid_Person.DataSource = XML_Person;
}
I want to do these Deserializing methods as one different Method. I want to write this method into a dll file.
I tried to do these:
private BindingList<Type> FromXML(BindingList<Type> type,string filepath)
{
XmlSerializer ser = new XmlSerializer(typeof(type));
FileStream fs = File.Open(filepath,FileMode.Open);
BindingList<Type> BL = (type)ser.Deserialize(fs);
fs.Close();
return BL;
}
But it did NOT work. Because i could not set BindingList type as Person.. What should I do ? Thanks.
Seems that you forgot to set your generic type parameter on your method declaration.
Try this:
public static class MySerializationHelper
{
public static class From
{
public TReturn XMLFile<TReturn>(string contents)
{
var serializer = new XmlSerializer(typeof(TReturn));
var fs = File.Open(filePath, FileMode.Open);
var result = (TReturn)serializer.Deserialize(fs);
fs.Close();
return result;
}
}
public static class To
{
public void XMLFile<TType>(TType object, string filePath)
{
// Serialize it here...
}
}
}
Than, you may simply use it, like:
var bindingList = MySerializationHelper.From.XmlFile<IBindingList<Person>>("Persons.xml");
var person = MySerializationHelper.From.XmlFile<Person>("Person_1.xml");
MySerializationHelper.To.XmlFile<IBindingList<Person>>(bindingList, "Persons_copy.xml");
MySerializationHelper.To.XmlFile<Person>(person, "Person_1_Copy.xml");
I want to serialize an object to XML, but I don't want to save it on the disk. I want to hold it in a XElement variable (for using with LINQ), and then Deserialize back to my object.
How can I do this?
You can use these two extension methods to serialize and deserialize between XElement and your objects.
public static XElement ToXElement<T>(this object obj)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
}
public static T FromXElement<T>(this XElement xElement)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(xElement.CreateReader());
}
USAGE
XElement element = myClass.ToXElement<MyClass>();
var newMyClass = element.FromXElement<MyClass>();
You can use XMLSerialization
XML serialization is the process of converting an object's public
properties and fields to a serial format (in this case, XML) for
storage or transport. Deserialization re-creates the object in its
original state from the XML output. You can think of serialization as
a way of saving the state of an object into a stream or buffer. For
example, ASP.NET uses the XmlSerializer class to encode XML Web
service messages
and XDocument Represents an XML document to achieve this
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace ConsoleApplication5
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
XmlSerializer xs = new XmlSerializer(typeof(Person));
Person p = new Person();
p.Age = 35;
p.Name = "Arnold";
Console.WriteLine("\n Before serializing...\n");
Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age,p.Name));
XDocument d = new XDocument();
using (XmlWriter xw = d.CreateWriter())
xs.Serialize(xw, p);
// you can use LINQ on elm now
XElement elm = d.Root;
Console.WriteLine("\n From XElement...\n");
elm.Elements().All(e => { Console.WriteLine(string.Format("element name {0} , element value {1}", e.Name, e.Value)); return true; });
//deserialize back to object
Person pDeserialized = xs.Deserialize((d.CreateReader())) as Person;
Console.WriteLine("\n After deserializing...\n");
Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age, p.Name));
Console.ReadLine();
}
}
}
and here is output
(Late answer)
Serialize:
var doc = new XDocument();
var xmlSerializer = new XmlSerializer(typeof(MyClass));
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, obj);
}
// now you can use `doc`(XDocument) or `doc.Root` (XElement)
Deserialize:
MyClass obj;
using(var reader = doc.CreateReader())
{
obj = (MyClass)xmlSerializer.Deserialize(reader);
}
ToXelement without Code Analysis issues, same answer as Abdul Munim but fixed the CA issues (except for CA1004, this cannot be resolved in this case and is by design)
public static XElement ToXElement<T>(this object value)
{
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
memoryStream = null;
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, value);
return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
finally
{
if (memoryStream != null)
{
memoryStream.Dispose();
}
}
}
What about
public static byte[] BinarySerialize(Object obj)
{
byte[] serializedObject;
MemoryStream ms = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
try
{
b.Serialize(ms, obj);
ms.Seek(0, 0);
serializedObject = ms.ToArray();
ms.Close();
return serializedObject;
}
catch
{
throw new SerializationException("Failed to serialize. Reason: ");
}
}