中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
珲春市| 汉中市| 民和| 六枝特区| 淮滨县| 平南县| 资讯| 清流县| 沅陵县| 息烽县| 郯城县| 苗栗县| 竹北市| 防城港市| 胶州市| 隆尧县| 枝江市| 公主岭市| 荣成市| 晴隆县| 内丘县| 临城县| 图木舒克市| 古浪县| 陵水| 前郭尔| 禄劝| 汝城县| 黎川县| 宜川县| 威远县| 平舆县| 阳泉市| 都匀市| 罗田县| 松原市| 襄垣县| 共和县| 苗栗市| 大庆市| 蕲春县|