範例:用 GZipStream 壓縮 JSON 字串

這是先前寫的測試 code,用來了解 JSON 字串經過 GZip 壓縮後能夠節省多少資料傳輸量。


class GZippedJsonDemo
{
    public void Run()
    {            
        SharedClasses.Student student1 = new SharedClasses.Student();

        // Serializes the object to a JSON string.
        string jsonStr = JsonConvert.SerializeObject(student1, Formatting.Indented);

        // GZip compress.
        byte[] zipped = Compress(jsonStr);
        Console.WriteLine("GZipped JSON serialized length: " + zipped.Length);

        // GZip decompress.
        string unZippedJsonStr = Decompress(zipped);

        // Deserialize the JSON string to an object.
        Type aType = Type.GetType("SharedClasses.Student");
        Student stu = (Student)JsonConvert.DeserializeObject(unZippedJsonStr, aType);

        Console.WriteLine(stu.Addr.City);
    }

    byte[] Compress(string jsonStr)
    {            
        MemoryStream zippedStream = new MemoryStream();            
        using (GZipStream gzip = new GZipStream(zippedStream, CompressionMode.Compress))
        {
            BinaryFormatter bfmt = new BinaryFormatter();
            bfmt.Serialize(gzip, jsonStr);
            gzip.Flush();                
        }

        byte[] zippedBuf = zippedStream.ToArray();            
        return zippedBuf;
    }

    string Decompress(byte[] zippedJson)
    {
        string jsonStr;

        MemoryStream zippedStream = new MemoryStream(zippedJson);            
        using (GZipStream gzip = new GZipStream(zippedStream, CompressionMode.Decompress))
        {
            BinaryFormatter bfmt = new BinaryFormatter();
            jsonStr = (string) bfmt.Deserialize(gzip);
        }

        return jsonStr;            
    }
}
延伸閱讀

Copyright © 2012. Huan-Lin 學習筆記 - All Rights Reserved
Powered by Blogger
Template Design by Cool Blogger Tutorials
Published by Templates Doctor