Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Object Convert To Other Data Format ( JSON, XML, Binary )
// Object Structure
[Serializable]
public class BasePerson
{
public string SerialNo { get; set; }
public Guid IdNo { get; set; }
}
[Serializable]
public class Person
:BasePerson
{
public string Name { get; set; }
public string Surname { get; set; }
public short Age { get; set; }
public AddressInfo AddressInfo { get; set; }
}
[Serializable]
public class AddressInfo
{
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
// Helper class for other data formats
// for binary serilization
public static class BinarySerilizationHelper
{
public static TObject Deserialize<TObject>(string binarydata)
{
byte[] b = Convert.FromBase64String(binarydata);
using (var stream = new MemoryStream(b))
{
var formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
return (TObject)formatter.Deserialize(stream);
}
}
public static string Serialize<TObject>(TObject obj)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Flush();
stream.Position = 0;
return Convert.ToBase64String(stream.ToArray());
}
}
}
// for XML Serilization
public static class XmlSerilizationHelper
{
public static string ToXML(Object obj)
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(stringwriter, obj);
return stringwriter.ToString();
}
public static BasePerson ToObject(string xml)
{
var stringReader = new System.IO.StringReader(xml);
var serializer = new XmlSerializer(typeof(Person));
return serializer.Deserialize(stringReader) as Person;
}
}
// Let's use our helper classes in console application :D
class Program
{
static void Main(string[] args)
{
// JSON
// Binary
// XML
AddressInfo address = new AddressInfo
{
Street = "Bülbül str.",
City = "İstanbul",
Country = "Turkey"
};
Person obj = new Person
{
AddressInfo = address,
IdNo = System.Guid.NewGuid(),
SerialNo = "SED23SU98",
Age = 13,
Name = "Yunus Emre",
Surname = "KESKIN"
};
// JSON
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
Console.WriteLine("---");
// XML
string xml = XmlSerilizationHelper.ToXML(obj);
Console.WriteLine(xml);
Console.WriteLine("---");
Person person = XmlSerilizationHelper.ToObject(xml) as Person;
// Binary Serilization
string binary = BinarySerilizationHelper.Serialize(obj);
Console.WriteLine(binary);
Person dummy = BinarySerilizationHelper.Deserialize<Person>(binary);
Console.WriteLine(dummy.IdNo);
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.