星期二, 7月 13, 2010

[Asp.Net] Json 序列化及反序列化

今天幫學弟測試了一下 Json 序列化及反序列化的簡單範例,也用了平常很少使用的泛型。
記錄一下以供日後參考。 畢竟AJAX常會用到json來傳輸資料。

使用以下範例需注意事項:
1.加入參考組件:組件 System.Runtime.Serialization (在 System.Runtime.Serialization.dll 中)
2.序列化的物件格式可自行修改自已自訂的格式
3.物件變數的命名需跟json的宣告名稱一致


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace ImagesNotes
{
    [Serializable]
    public class ImageObj
    {
        //public int imageID;
        public string divid;
        public int  x;
        public int y;
        public int w;
        public int h;
        public string src;

        public ImageObj() 
        { 

        }
    }
    [Serializable]
    public class ImagesSet
    {
        public List images = new List();
        
        public ImagesSet()
        {
            //myImgesList.Add();
        }
    }

    public class JsonSerialize
    {
        public JsonSerialize()
        { 

        }

        /// 
        /// obj to json string
        /// 
        public  string ToJson(T obj)
        {
            DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ds.WriteObject(ms, obj);
            string strJSON = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return strJSON;
        }

        /// 
        /// string json to obj
        /// 
        public T Deserialize(string sJson) where T : class
        {
            DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sJson));
            T obj = (T)ds.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }
} 

//單一的圖片物件宣告
 string imgStr = " {\"divid\": \"01s\",\"x\": 341,\"y\": 103,\"src\": \"photo/SPIDERMAN%20(THE%20MOVIE).png\",\"h\": 128,\"w\": 128}";


//圖片陣列宣告
 string imgStr2 = "{\"images\": [{\"divid\":\"01s\",\"x\": 232,\"y\" :173,\"src\" :\"photo/SPIDERMAN%20(THE%20MOVIE).png\",\"h\" :127,\"w\" :148},{\"divid\":\"02s\",\"x\": 37,\"y\" :141,\"src\" :\"photo/SPIDERMAN%20(THE%20MOVIE).png\",\"h\" :128,\"w\" :128},]}";


ImagesNotes.JsonSerialize js = new ImagesNotes.JsonSerialize();

ImagesNotes.ImageObj img = js.Deserialize(imgStr);

ImagesNotes.ImagesSet img2 = js.Deserialize( imgStr2);

string imgStr3 = js.ToJson(img2); 
Reference:
.NET Framewok 3.5 中 JSON 序列化和反序列化的简单实现
MSDN : DataContractJsonSerializer 類別
JSON Serializer / How to?
ScriptManager EnablePageMethods 與 JSON 序列化
[C#.NET][VB.NET] 一般 / 泛型 Generic Collection 集合型別介紹(此篇基本介紹,蠻祥細的)

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails