You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本文件JSON反序列化为Dictionary<string,string>及解决反序列化报错

解决Newtonsoft.Json反序列化多JSON对象文件的问题

问题根源

你当前的错误是因为每次向文件写入时,都将整个FileList序列化为完整的JSON对象并追加到文件末尾,导致文件内容是多个独立的JSON对象直接拼接(比如}{连在一起)。而Newtonsoft.Json只能解析单个合法的JSON结构,因此反序列化时会因遇到额外内容报错。

方案1:修正写入逻辑(推荐)

直接覆盖文件而非追加,确保文件始终只保存一个完整的Dictionary JSON结构:

rectangleName = @"d:\Rectangles\rectangle" + saveRectanglesCounter + ".bmp";
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
    FileList,
    Formatting.Indented // 格式化输出
);

// 移除StreamWriter的第二个参数true,默认以覆盖模式写入
using (StreamWriter sw = new StreamWriter(@"d:\rectangles.txt"))
{
    sw.Write(json);
    // using块会自动释放资源,无需手动调用Close()
}

此时文件内始终是单个合法的JSON对象,反序列化直接使用以下代码即可:

string fileContent = File.ReadAllText(@"d:\rectangles.txt");
FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(fileContent);

方案2:处理已存在的多JSON内容

如果已经生成了包含多个JSON对象的文件,可以拆分每个独立的JSON片段,逐个解析后合并到Dictionary中:

string fileContent = File.ReadAllText(@"d:\rectangles.txt");
// 按"}{"拆分JSON片段,移除空条目
var jsonSegments = fileContent.Split(new[] { "}{" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(segment => 
    {
        // 给每个片段补全首尾的{},确保是合法的JSON对象
        var processedSegment = segment;
        if (!processedSegment.StartsWith("{")) processedSegment = "{" + processedSegment;
        if (!processedSegment.EndsWith("}")) processedSegment = processedSegment + "}";
        return processedSegment;
    });

FileList = new Dictionary<string, string>();
foreach (var segment in jsonSegments)
{
    var tempDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(segment);
    foreach (var kvp in tempDict)
    {
        // 处理重复键:此处选择覆盖旧值,可根据需求改为跳过
        FileList[kvp.Key] = kvp.Value;
    }
}

内容的提问来源于stack exchange,提问作者jhon last

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:10:39