範例:用 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;            
    }
}
延伸閱讀

2 則留言:

  1. 大大,是否可能直接寫出一些"數據"。(Sorry, 我偷懶)

    回覆刪除
  2. Hi Bruce,
    資料大小的比較,往往跟用來測試的資料本身有關。由於我沒有做很詳細的測試,所以沒有把數據貼上來。先前已經有人做了一些比較詳細的測試,可以參考:
    http://james.newtonking.com/archive/2010/01/01/net-serialization-performance-comparison.aspx
    我記得還有看過一篇比較壓縮過的 JSON 和 BSON 的文章,一時找不到了。強調節省資料的序列化格式,另外還有 MessagePack 和 Protocal Buffers,也可以考慮。

    回覆刪除

技術提供:Blogger.
回頂端⬆️