onsdag 1 april 2009

DEVTIPS #6 JSON Serialization with .NET

.NET 3.5 Has JSON serialization built-in.
Include these references:

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;

Make a serializable object defenition (class):
[Serializable]
public class JsonQuery
{
    public string licenseKey;
    public string layoutName;
    public List items;
}

Make two generic functions for serialize and deserialize JSON Message:
    private object JsonDeserialize(string json, Type type)
    {
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type);
        object o = dcjs.ReadObject(ms);
        ms.Close();
        return o;
    }

    private string JsonSerialize(object obj, Type type, string callback)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, obj);
        string json = Encoding.Default.GetString(ms.ToArray());
        ms.Close();
        return callback + "(" + json + ")";
    }

Inga kommentarer: