Created
February 10, 2017 09:51
-
-
Save margani/82f71b137c50ffe13a894b3575c1b961 to your computer and use it in GitHub Desktop.
This code demonstrates 4 methods of json serialization and deserialization
This file contains 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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment