anduin revised this gist 7 months ago. Go to revision
1 file changed, 57 insertions
Program.cs(file created)
| @@ -0,0 +1,57 @@ | |||
| 1 | + | using System; | |
| 2 | + | using System.Collections.Generic; | |
| 3 | + | using System.IO; | |
| 4 | + | using System.IO.Compression; | |
| 5 | + | using System.Text.Json; | |
| 6 | + | ||
| 7 | + | namespace JsonToGzip | |
| 8 | + | { | |
| 9 | + | class Program | |
| 10 | + | { | |
| 11 | + | static void Main(string[] args) | |
| 12 | + | { | |
| 13 | + | // 输入输出文件路径 | |
| 14 | + | string inputJsonPath = @"C:\Users\xuef\Downloads\a.json"; | |
| 15 | + | string outputTxtPath = "files.txt"; | |
| 16 | + | string outputGzPath = "files.txt.gz"; | |
| 17 | + | ||
| 18 | + | // 读取 JSON 文件内容 | |
| 19 | + | string jsonContent = File.ReadAllText(inputJsonPath); | |
| 20 | + | ||
| 21 | + | // 使用 System.Text.Json 解析 JSON | |
| 22 | + | using JsonDocument document = JsonDocument.Parse(jsonContent); | |
| 23 | + | JsonElement root = document.RootElement; | |
| 24 | + | ||
| 25 | + | // 存储输出的每一行 | |
| 26 | + | List<string> lines = new List<string>(); | |
| 27 | + | ||
| 28 | + | // 根据要求,输出顶层 "cr:itemType" 的属性名(而非它的值) | |
| 29 | + | if (root.TryGetProperty("cr:itemType", out JsonElement itemTypeElement)) | |
| 30 | + | { | |
| 31 | + | lines.Add("cr:itemType"); | |
| 32 | + | } | |
| 33 | + | ||
| 34 | + | // 遍历 "cr:files" 对象,将每个文件的键(即文件路径)添加到输出行中 | |
| 35 | + | if (root.TryGetProperty("cr:files", out JsonElement filesElement)) | |
| 36 | + | { | |
| 37 | + | foreach (JsonProperty file in filesElement.EnumerateObject()) | |
| 38 | + | { | |
| 39 | + | lines.Add(file.Name); | |
| 40 | + | } | |
| 41 | + | } | |
| 42 | + | ||
| 43 | + | // 将结果写入 files.txt,每个路径一行 | |
| 44 | + | File.WriteAllLines(outputTxtPath, lines); | |
| 45 | + | ||
| 46 | + | // 使用 GZipStream 压缩生成 files.txt.gz | |
| 47 | + | using (FileStream originalFileStream = File.OpenRead(outputTxtPath)) | |
| 48 | + | using (FileStream compressedFileStream = File.Create(outputGzPath)) | |
| 49 | + | using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionLevel.Optimal)) | |
| 50 | + | { | |
| 51 | + | originalFileStream.CopyTo(compressionStream); | |
| 52 | + | } | |
| 53 | + | ||
| 54 | + | Console.WriteLine("生成文件 {0} 成功。", outputGzPath); | |
| 55 | + | } | |
| 56 | + | } | |
| 57 | + | } | |
Newer
Older