如何在JSON反序列化时实习嵌套字典的所有字符串键?
解决方案
要在反序列化时自动对所有嵌套字典的字符串键执行string.Intern(),可以通过自定义JsonConverter拦截字典的反序列化过程,直接完成键的实习操作,无需手动遍历修改。
1. 自定义字典转换器
针对Dictionary<string, TValue>类型编写转换器,在读取JSON属性键时调用string.Intern():
public class InternedDictionaryConverter<TValue> : JsonConverter { public override bool CanConvert(Type objectType) { // 匹配任意Dictionary<string, TValue>类型 return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && objectType.GetGenericArguments()[0] == typeof(string); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; // 读取JSON对象 var jObject = JObject.Load(reader); var dictionary = (IDictionary<string, TValue>)Activator.CreateInstance(objectType); foreach (var property in jObject.Properties()) { // 对键执行Intern,再反序列化对应的值 var internedKey = string.Intern(property.Name); var value = property.Value.ToObject<TValue>(serializer); dictionary.Add(internedKey, value); } return dictionary; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // 序列化时沿用默认逻辑 serializer.Serialize(writer, value); } }
2. 应用转换器
有两种方式启用这个转换器:
方式一:全局生效(所有Dictionary<string, T>都会被处理)
在反序列化时配置JsonSerializerSettings:
var settings = new JsonSerializerSettings(); settings.Converters.Add(new InternedDictionaryConverter<object>()); // 泛型转换器会自动匹配所有TValue类型的字典 var jeffInstance = JsonConvert.DeserializeObject<Jeff>(jsonString, settings);
方式二:仅针对特定属性生效
直接在Jeff类的字典属性上标记特性:
public class Jeff { [JsonProperty("string_to_int")] [JsonConverter(typeof(InternedDictionaryConverter<Dictionary<string, Dictionary<string, int>>>))] public Dictionary<string, Dictionary<string, Dictionary<string, int>>> StringToInt; } // 反序列化无需额外配置 var jeffInstance = JsonConvert.DeserializeObject<Jeff>(jsonString);
说明
这个转换器会递归处理所有嵌套层级的Dictionary<string, T>——反序列化内部字典时同样会触发转换器逻辑,因此不管嵌套多少层,所有字符串键都会被自动Intern()。由于你的键来自有限词汇集合,这种方式能有效减少重复字符串对象的创建,节省内存开销。
内容的提问来源于stack exchange,提问作者Jeffery Chow
相关产品推荐
相关产品推荐

