亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

C#壓縮JSON數據的技巧

c#
小樊
87
2024-07-11 09:44:39
欄目: 編程語言

在C#中壓縮JSON數據可以使用GZipStream類。以下是一個示例代碼:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

public class JsonCompression
{
    public static string Compress(string json)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(json);
        using (MemoryStream ms = new MemoryStream())
        {
            using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
            {
                zip.Write(buffer, 0, buffer.Length);
            }

            ms.Position = 0;
            byte[] compressed = new byte[ms.Length];
            ms.Read(compressed, 0, compressed.Length);

            byte[] gzBuffer = new byte[compressed.Length + 4];
            System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
            System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
            return Convert.ToBase64String(gzBuffer);
        }
    }

    public static string Decompress(string compressedJson)
    {
        byte[] gzBuffer = Convert.FromBase64String(compressedJson);
        using (MemoryStream ms = new MemoryStream())
        {
            int msgLength = BitConverter.ToInt32(gzBuffer, 0);
            ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

            byte[] buffer = new byte[msgLength];

            ms.Position = 0;
            using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
            {
                zip.Read(buffer, 0, buffer.Length);
            }

            return Encoding.UTF8.GetString(buffer);
        }
    }
}

使用示例:

string json = "{\"name\": \"John\", \"age\": 30}";
string compressedJson = JsonCompression.Compress(json);
string decompressedJson = JsonCompression.Decompress(compressedJson);

Console.WriteLine($"Original JSON: {json}");
Console.WriteLine($"Compressed JSON: {compressedJson}");
Console.WriteLine($"Decompressed JSON: {decompressedJson}");

在上面的示例中,Compress方法將JSON數據壓縮成Base64字符串,而Decompress方法將壓縮后的Base64字符串解壓縮為原始JSON數據。

0
项城市| 合作市| 房山区| 乐昌市| 县级市| 桦甸市| 徐水县| 静海县| 河间市| 邯郸县| 闻喜县| 兴宁市| 阳春市| 东兰县| 攀枝花市| 娱乐| 姜堰市| 广安市| 西林县| 海林市| 监利县| 淮南市| 治多县| 大化| 西乌珠穆沁旗| 大方县| 进贤县| 浪卡子县| 大宁县| 垣曲县| 广宗县| 麻阳| 武平县| 伊宁市| 乌兰县| 舞阳县| 辽宁省| 陇南市| 噶尔县| 磐安县| 凤凰县|