Visar inlägg med etikett json. Visa alla inlägg
Visar inlägg med etikett json. Visa alla inlägg

onsdag 1 april 2009

DEVTIPS #7 JSON Message

Class defenitions for serialization:
[Serializable]
public class JsonQuery
{
    public string licenseKey;
    public string layoutName;
    public List<JsonQueryItem> items;
}

[Serializable]
public class JsonQueryItem
{
    public string fieldRef;
    public string comparison;
    public string value;
}

Javascript JSON Message:
   var query = {
                licenseKey: "3c67897",
                layoutName: "hemma",
                items: [
                    {
                        fieldRef: "PRODUCT_CODE",
                        comparison: "Contains",
                        value: "hepa"
                    }
                ]
            };

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 + ")";
    }