使用 system.text.json 序列化时,字典的键会自动转换为字符串。如果键是枚举类型,默认会序列化为数字;如果需要序列化为枚举名称字符串,需要配置 jsonserializeroptions 中的 converters 属性并添加 jsonstringenumconverter。

JsonSerializer.Serialize() 对非字符串键的处理逻辑是什么
该方法在序列化过程中会将字典的所有键转换为字符串形式。对于整数键,直接转为数字字符串;对于枚举键,若未配置转换器则转为整数值,配置后转为枚举名称。

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public enum Status { Active, Inactive }
public class Program {
public static void Main() {
var dict = new Dictionary<status string> {
{ Status.Active, "Running" },
{ Status.Inactive, "Stopped" }
};
// 默认行为:枚举键转为数字
var optionsDefault = new JsonSerializerOptions();
Console.WriteLine(JsonSerializer.Serialize(dict, optionsDefault));
// 配置行为:枚举键转为字符串
var optionsString = new JsonSerializerOptions();
optionsString.Converters.Add(new JsonStringEnumConverter());
Console.WriteLine(JsonSerializer.Serialize(dict, optionsString));
}
}
</status>
预期输出:
{"0":"Running","1":"Stopped"}
{"Active":"Running","Inactive":"Stopped"}
如何自定义字典键的序列化格式
可以通过实现 JsonConverter 来完全控制序列化过程。在 Write 方法中遍历字典,手动将键转换为目标字符串格式,然后写入 JSON 对象。
通过 Playwright + HTTP 实现网页搜索与内容抓取,无需 API 密钥,支持国内 Bing CN 与国际 DuckDuckGo,自动获取排名前列的页面内容。

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
public class CustomDictConverter : JsonConverter<dictionary string>> {
public override Dictionary<int string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, Dictionary<int string> value, JsonSerializerOptions options) {
writer.WriteStartObject();
foreach (var kvp in value) {
// 自定义键的格式,例如加上前缀
writer.WriteStringProperty($"key_{kvp.Key}", kvp.Value);
}
writer.WriteEndObject();
}
}
public class Program {
public static void Main() {
var dict = new Dictionary<int string> { { 1, "A" }, { 2, "B" } };
var options = new JsonSerializerOptions();
options.Converters.Add(new CustomDictConverter());
Console.WriteLine(JsonSerializer.Serialize(dict, options));
}
}
</int></int></int></dictionary>
预期输出:
{"key_1":"A","key_2":"B"}
当字典中包含 null 值时,JSON 输出结果如何
在序列化时,如果字典的值(Value)为 null,根据 JsonSerializerOptions 的配置,可能会省略该键值对或将其序列化为 null。默认情况下,System.Text.Json 会保留 null 值。
using System;
using System.Collections.Generic;
using System.Text.Json;
public class Program {
public static void Main() {
var dict = new Dictionary<string string> {
{ "a", "value" },
{ "b", null }
};
Console.WriteLine(JsonSerializer.Serialize(dict));
}
}
</string>
预期输出:
{"a":"value","b":null}










