首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >提取.JSON文件中.GZ文件的内容

提取.JSON文件中.GZ文件的内容
EN

Stack Overflow用户
提问于 2019-10-10 20:41:22
回答 1查看 1.2K关注 0票数 0

使用下面的代码,我可以下载包含.gz文件的.json文件,但无法将.json文件中的内容提取到内存中。当我期望text变量包含存储在.json文件中的JSON时,下面的代码将导致它是一个空字符串。

文件结构

  1. example.gz

1a.example.json

源代码

代码语言:javascript
运行
复制
// Identify the location of the .gz file containing the results of the export

            string jobOutputGzipLocation = null;
            for (var i = 0; i < 5; i++)
            {
                var httpResponse2 = await _httpClient.GetAsync($"api/v2/jobs/{jobId}");
                if (httpResponse2.IsSuccessStatusCode)
                {
                    var httpMessage2 = await httpResponse2.Content.ReadAsStringAsync();
                    var httpJsonMessage2 = JObject.Parse(httpMessage2);
                    if (string.Equals(httpJsonMessage2.Value<string>("status"), "completed", StringComparison.OrdinalIgnoreCase)) {
                        jobOutputGzipLocation = httpJsonMessage2.Value<string>("location");
                        break;
                    }
                }

                await Task.Delay(3000);
            }
            if (string.IsNullOrEmpty(jobOutputGzipLocation))
                throw new Exception("Unable to identify jobOutputGzipLocation from the job results.");

// Extract the contents of the .gz file into memory

            var httpResponse3 = await _httpClient.GetAsync(jobOutputGzipLocation);
            if (!httpResponse3.IsSuccessStatusCode) throw new Exception("Shoot3");
            var httpMessage3 = await httpResponse3.Content.ReadAsStreamAsync();

            using (var ms = new MemoryStream())
            {
                using (var gZipStream = new GZipStream(httpMessage3, CompressionMode.Decompress))
                {
                    gZipStream.CopyTo(ms);
                }
                using (var sr = new StreamReader(ms, Encoding.UTF8))
                {
                    var text = sr.ReadToEnd();
                }
            }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-10 21:46:28

此代码正在工作:

代码语言:javascript
运行
复制
using (var ss = new FileStream("log.txt.gz", FileMode.Open))
        using (var ms = new MemoryStream())
        {
            using (var gZipStream = new GZipStream(ss, CompressionMode.Decompress))
            {
                gZipStream.CopyTo(ms);
            }
            ms.Seek(0, SeekOrigin.Begin);  // so I put the stream to the initial position
            using (var sr = new StreamReader(ms, Encoding.UTF8))
            {
                var text = sr.ReadToEnd();
            }
        }

从我的测试中,如果我不重置名为"ms“的流的位置,我将变量"text”作为空字符串。

如果我把流放到初始位置,我就得到了需要的结果。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58330780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档