Created
August 24, 2015 08:16
-
-
Save mattkruskamp/789c872904f12f128ce7 to your computer and use it in GitHub Desktop.
Deserializating Xml and Json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[DataContract(Name="Client")] | |
public class ClientData | |
{ | |
[DataMember] | |
public int ClientId { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new Serializer<ClicntData>().FromJson(myHappyString); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment