Created
August 11, 2012 16:25
-
-
Save aschearer/3325579 to your computer and use it in GitHub Desktop.
Compressing Json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.IO.Compression; | |
using System.Runtime.Serialization.Json; | |
using System.Text; | |
namespace Petunk.Common.Models | |
{ | |
public class StreamUtilities | |
{ | |
public static Stream StringToStream(string json) | |
{ | |
byte[] byteArray = Encoding.UTF8.GetBytes(json); | |
return new MemoryStream(byteArray); | |
} | |
public static byte[] Compress<T>(T setting) | |
{ | |
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); | |
byte[] compressedBytes; | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
using (GZipStream compressedStream = new GZipStream(memoryStream, CompressionMode.Compress, true)) | |
{ | |
serializer.WriteObject(compressedStream, setting); | |
} | |
compressedBytes = memoryStream.ToArray(); | |
} | |
return compressedBytes; | |
} | |
public static T Decompress<T>(Stream compressedStream) | |
{ | |
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); | |
T restoredData; | |
using (GZipStream decompressedStream = new GZipStream(compressedStream, CompressionMode.Decompress, true)) | |
{ | |
restoredData = (T)serializer.ReadObject(decompressedStream); | |
} | |
return restoredData; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment