Deserializing XML and Json in C#
I threw together a quick class to serialize and deserialize objects to xml and json in C#. This code shouldn't be considered production as you can see there is no error checking and correction. Either way, here you go:
public class Serializer<T>
{
public T FromXml(string xmlString)
{
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xmlString));
DataContractSerializer ser = new DataContractSerializer(typeof(T));
T item = (T)ser.ReadObject(ms);
ms.Close();
return item;
}
public T FromJson(string jsonString)
{
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
T item = (T)ser.ReadObject(ms);
ms.Close();
return item;
}
public string ToXml(T item)
{
DataContractSerializer ser = new DataContractSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, item);
string xml = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
ms.Close();
return xml;
}
public string ToJson(T item)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, item);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
ms.Close();
return json;
}
}
Here is an example business object for it:
[DataContract(Name="Client")]
public class ClientData
{
[DataMember]
public int ClientId { get; set; }
}
And here is an example usage:
new Serializer<ClicntData>().FromJson(myHappyString);
Happy Coding