Can I decompress and deserialize a file using streams?

前端 未结 2 511
Happy的楠姐
Happy的楠姐 2020-12-02 02:03

My application serializes an object using Json.Net, compresses the resulting JSON, then saves this to file. Additionally the application can load an object from one of these

2条回答
  •  独厮守ぢ
    2020-12-02 02:36

    For those looking for an idea how to use the extensions from @dbc in uwp apps, I modified the code to this - where the StorageFile is a file you have access to write to.

    public static async void SerializeToFileCompressedAsync(object value, StorageFile file, JsonSerializerSettings settings = null)
    {
        using (var stream = await file.OpenStreamForWriteAsync())
            SerializeCompressed(value, stream, settings);
    }
    
    public static void SerializeCompressed(object value, Stream stream, JsonSerializerSettings settings = null)
    {
        using (var compressor = new GZipStream(stream, CompressionMode.Compress))
        using (var writer = new StreamWriter(compressor))
        {
            var serializer = JsonSerializer.CreateDefault(settings);
            serializer.Serialize(writer, value);
        }
    }
    
    public static async Task DeserializeFromFileCompressedAsync(StorageFile file, JsonSerializerSettings settings = null)
    {
        using (var stream = await file.OpenStreamForReadAsync())
            return DeserializeCompressed(stream, settings);
    }
    
    public static T DeserializeCompressed(Stream stream, JsonSerializerSettings settings = null)
    {
        using (var compressor = new GZipStream(stream, CompressionMode.Decompress))
        using (var reader = new StreamReader(compressor))
        using (var jsonReader = new JsonTextReader(reader))
        {
            var serializer = JsonSerializer.CreateDefault(settings);
            return serializer.Deserialize(jsonReader);
        }
    }
    

提交回复
热议问题