91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
许昌市| 开鲁县| 北流市| 齐河县| 三江| 勐海县| 太和县| 云和县| 托克逊县| 大港区| 留坝县| 蛟河市| 苍梧县| 喀喇沁旗| 凤凰县| 汉阴县| 朔州市| 宾阳县| 远安县| 潜江市| 布拖县| 泸溪县| 临桂县| 伊川县| 洛阳市| 保德县| 英吉沙县| 资源县| 盘山县| 确山县| 常熟市| 望都县| 广州市| 邢台县| 定安县| 南丹县| 屏东市| 新泰市| 高陵县| 中阳县| 新密市|