Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Build an OpenVPN server on android device Preparation An android device, in this case, Sony xperia Z is used Root permission required Linux Deploy for deploy i... LogonUser Function : impersonate a windows user // This sample demonstrates the use of the WindowsIdentity class to impersonate a user. // IMPORTANT NOTES:  // This sample can be run only ...
Blog Archive
Stats
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;
    }
}