c#

C#压缩JSON数据的技巧

小樊
94
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
看了该问题的人还看了