.NET读取格式错误的JSON文件:如何处理log.json非标准结构
在.NET中处理非标准的行分隔JSON日志文件
嘿,这种每行一个独立JSON对象的格式其实挺常见的(业内叫JSON Lines),虽然确实不符合标准的JSON数组结构,在.NET里有几种很实用的处理方式,我给你详细说说:
方法一:先修正文本格式再反序列化(适合小文件)
如果你的日志文件不大,最直接的方式就是先把文件内容转换成标准的JSON数组格式,再正常反序列化:
using System.IO; using System.Text.Json; // 读取原始文件内容 string rawLogContent = File.ReadAllText("log.json"); // 修正为标准JSON数组:开头加[,结尾加],把独立对象的边界}{替换成},{ // 注意:如果文件里的对象之间是换行分隔,可把替换内容改成"}\r\n{"或"}\n{" string validJsonArray = $"[{rawLogContent.Replace("}{", "},{")}]"; // 反序列化为日志实体列表 var logEntries = JsonSerializer.Deserialize<List<LogEntry>>(validJsonArray); // 定义对应的日志实体类,属性名要和JSON键对应(也可以用JsonPropertyName特性自定义映射) public class LogEntry { public DateTime Time { get; set; } public string Function { get; set; } public int Line { get; set; } public string UserWindows { get; set; } public string Level { get; set; } public string Message { get; set; } }
方法二:逐行读取并反序列化(适合大文件)
如果日志文件体积很大,一次性读取整个文件会占用过多内存,推荐逐行读取每个JSON对象,逐个反序列化,这样内存占用会低很多:
用System.Text.Json(.NET Core 3.0+ 内置)
using System.IO; using System.Text.Json; List<LogEntry> logEntries = new List<LogEntry>(); // 逐行读取文件 using (var streamReader = new StreamReader("log.json")) { string line; while ((line = streamReader.ReadLine()) != null) { // 跳过可能的空行 if (string.IsNullOrWhiteSpace(line)) continue; // 反序列化当前行的JSON对象 var logEntry = JsonSerializer.Deserialize<LogEntry>(line); logEntries.Add(logEntry); } }
用Newtonsoft.Json(Json.NET,老牌第三方库)
如果你习惯用Json.NET,代码逻辑类似:
using System.IO; using Newtonsoft.Json; List<LogEntry> logEntries = new List<LogEntry>(); using (var streamReader = new StreamReader("log.json")) using (var jsonReader = new JsonTextReader(streamReader)) { var serializer = new JsonSerializer(); // 逐个读取JSON对象 while (jsonReader.Read()) { // 只处理对象开始的节点 if (jsonReader.TokenType == JsonToken.StartObject) { var logEntry = serializer.Deserialize<LogEntry>(jsonReader); logEntries.Add(logEntry); } } }
额外提示
这种行分隔的JSON格式(JSON Lines)其实是一种被广泛使用的日志格式,很多日志框架都会输出这种格式。如果以后遇到类似的文件,不用觉得是“错误格式”,它本身就是一种标准的日志存储方式哦。
内容的提问来源于stack exchange,提问作者warkanix
相关产品推荐
相关产品推荐

