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

C# .Net中保存字典到JSON文件时如何设置缩进距离?

解决Newtonsoft.Json自定义缩进数量的问题
  • Formatting是枚举类型,Formatting.Indented仅作为开启缩进的标记,无法直接修改它的值来调整缩进数量。不需要更换命名空间,借助Newtonsoft.Json自带的JsonSerializerSettings就能实现自定义缩进配置。

具体实现代码如下:

// 定义字典(路径字符串加@避免反斜杠转义问题)
var param_dict = new Dictionary<string, object>
{
    { "config_path", @"D:\WORK_2023\Helloworld in C" },
};

// 配置序列化参数
var serializeSettings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented,
    Indentation = 4,  // 设置缩进为4个空格
    IndentChar = ' '  // 指定缩进用空格,想用制表符可改为'\t'
};

// 序列化并写入文件
string json = JsonConvert.SerializeObject(param_dict, serializeSettings);
File.WriteAllText(param_file_path, json);

说明:

  • Indentation属性控制缩进的数量,设置为4即可实现4个空格的缩进效果。
  • IndentChar指定缩进使用的字符,默认是空格,可根据需求替换为制表符。
  • 路径字符串前加@是为了避免反斜杠被转义,确保JSON文件中保存的路径格式正确。

内容的提问来源于stack exchange,提问作者4daJKong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:07:03