Created
October 11, 2021 13:15
-
-
Save rianjs/d8da09b3b2355e9f02edfec63748dd78 to your computer and use it in GitHub Desktop.
Serializing to and from a C# POCO using System.Text.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; | |
using System.IO; | |
using System.IO.Compression; | |
using System.Text.Json; | |
namespace CodatIngestion | |
{ | |
public static class CompressionUtils | |
{ | |
public static byte[] ToJsonSerializedGzipBytes<T>(T value, JsonSerializerOptions jsonOpts) | |
{ | |
if (value is null) | |
{ | |
return null; | |
} | |
if (jsonOpts is null) | |
{ | |
throw new NullReferenceException(nameof(jsonOpts)); | |
} | |
var jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(value, jsonOpts); | |
using (var dest = new MemoryStream()) | |
using (var gz = new GZipStream(dest, CompressionMode.Compress)) | |
{ | |
gz.Write(jsonUtf8Bytes, 0, jsonUtf8Bytes.Length); | |
gz.Close(); | |
return dest.ToArray(); | |
} | |
} | |
public static T FromJsonSerializedGzipBytes<T>(byte[] jsonSerializedGzipBytes, JsonSerializerOptions jsonOpts) | |
{ | |
if (jsonSerializedGzipBytes is null || jsonSerializedGzipBytes.Length == 0) | |
{ | |
return default; | |
} | |
if (jsonOpts is null) | |
{ | |
throw new NullReferenceException(nameof(jsonOpts)); | |
} | |
using (var compressed = new MemoryStream(jsonSerializedGzipBytes)) | |
using (var gz = new GZipStream(compressed, CompressionMode.Decompress)) | |
using (var dest = new MemoryStream()) | |
{ | |
gz.CopyTo(dest); | |
var jsonBytes = dest.ToArray(); | |
var jsonReader = new Utf8JsonReader(jsonBytes); | |
var deserialized = JsonSerializer.Deserialize<T>(ref jsonReader, jsonOpts); | |
return deserialized; | |
} | |
} | |
} | |
} |
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
var deserializedJson = CompressionUtils.FromJsonSerializedGzipBytes<T>(gzippedPayload, jsonOpts); | |
var serialized = CompressionUtils.ToJsonSerializedGzipBytes(deserializedJson, jsonOpts); | |
var samePayload = serialized.SequenceEqual(payload.GzipJson); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment