You need to enable JavaScript to run this app. 替换IDictionary<string,string>的同JSON序列化低耦合抽象C#结构选型
优惠活动
大模型
产品
解决方案
定价
更多

替换IDictionary<string,string>的同JSON序列化低耦合抽象C#结构选型

适配System.Text.Json的低耦合参数字典选型

基础参考示例

以下为基于System.Text.Json的可运行序列化示例,默认输出带缩进的嵌套键值对JSON结构:

using System;
using System.Collections.Generic;
using System.Text.Json;
                    
public class Program
{
    public static void Main()
    {
        var payload = new Payload();
        payload.Id = "1001";
        payload.PassthroughParameters.Add("Foo", "Bar");
        var jsonString = JsonSerializer.Serialize(payload, new JsonSerializerOptions {
            WriteIndented = true
        });
        Console.WriteLine(jsonString);
        // 输出结果:
        // {
        //   "Id": "1001",
        //   "PassthroughParameters": {
        //     "Foo": "Bar"
        //   }
        // }
    }
    
    public class Payload
    {
        public string Id { get; set; }
        public IDictionary<string, string> PassthroughParameters { get; set; } = new Dictionary<string, string>();
    }
}

核心选型解答

满足所有需求的最优选型为IReadOnlyDictionary<string, string>,对应替换后的Payload类定义为:

public class Payload
{
    public string Id { get; set; }
    // 替换原IDictionary类型为只读字典抽象
    public IReadOnlyDictionary<string, string> PassthroughParameters { get; set; } = new Dictionary<string, string>();
}

选型匹配性说明

  • 序列化结果完全一致:System.Text.Json对实现IReadOnlyDictionary<string, string>的类型,序列化逻辑与原IDictionary<string, string>完全一致,会直接生成嵌套键值对的JSON对象,不会产生结构偏移、字段差异,和现有输出逐字匹配
  • 抽象层级最高:该类型是覆盖字典键值对结构的最小必要抽象,不会暴露Add、Remove、索引器赋值等可变操作接口,从类型层面减少payload.PassthroughParameters["Foo"]这类直接索引式读写带来的耦合,既可以让调用方明确知道该参数集合不支持随意修改,也能避免因为隐式修改参数集合带来的非预期逻辑问题
  • 流程流转无阻塞:该类型可以直接透传给接收IReadOnlyDictionary、IEnumerable<KeyValuePair>等参数的内部处理方法,不需要额外类型转换,完全满足整体传递参数给业务流程的使用场景

选型避坑说明

  • 不要使用object作为属性类型:虽然运行时可挂载字典实例实现序列化,但完全丢失编译期类型约束,容易传入非字典类型导致序列化结果偏移,不属于“结果固定、可预期”的抽象类型
  • 不要使用IEnumerable<KeyValuePair<string, string>>作为属性类型:System.Text.Json会将该类型序列化为键值对对象组成的数组,和原有的嵌套对象JSON结构完全不匹配,无法满足输出一致的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 05:36:04