class JsonSerializationProgram
{
static void Main(string[] args)
{
var person = new Person
{
firstName = "John",
lastName = "Doe",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
Method1(person);
Method2(person);
Method3(person);
Method4(person);
Console.WriteLine("\r\nFinished.");
Console.ReadLine();
}
#region Method1
private static void Method1(Person person)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(person);
var anotherObject = serializer.Deserialize(json, typeof(Person));
}
#endregion
#region Method2
private static void Method2(Person person)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
var anotherObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
var anotherJObject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
dynamic anotherDynamicObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
}
#endregion
#region Method3
private static void Method3(Person person)
{
var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person));
var output = "";
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, person);
output = Encoding.Default.GetString(ms.ToArray());
}
using (var ms = new MemoryStream(Encoding.Default.GetBytes(output)))
{
var anotherObject = ser.ReadObject(ms) as Person;
}
}
#endregion
#region Method4
private static void Method4(Person person)
{
var json = NetJSON.NetJSON.Serialize(person);
var anotherObject = NetJSON.NetJSON.Deserialize<Person>(json);
}
#endregion
}
public class MyDate
{
public int year;
public int month;
public int day;
}
public class Person
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}