Searialize object as JSON
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
class Program
{
static void Main(string[] args)
{
Person person = new Person("Bruce", "Tsai");
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, person);
ms.Close();
string json = Encoding.Default.GetString(ms.ToArray());
Console.WriteLine(json);
Console.Read();
}
}
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
JSONHelper
public class JSONHelper
{
public static string ToJson(object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
ms.Close();
string json = Encoding.UTF8.GetString(ms.ToArray());
return json;
}
public static T ParseJson<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
obj = (T)ser.ReadObject(ms);
ms.Close();
return obj;
}
}