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

如何用C#+Restclient.Net+Newtonsoft处理动态键名JSON数据

解决方案

核心思路是用Dictionary<string, T>替代固定字段来接收动态键的entryPerArea对象,Newtonsoft.Json原生支持将动态键的JSON对象反序列化为字典,完美适配键名/数量变化的场景。

1. 定义适配的C#类

假设你的JSON结构大致如下:

{
"deliveryAreas": ["North", "South", "East"],
"entryPerArea": {
"North": 50,
"South": 30,
"East": 45
}
}

对应的C#类定义:

public class DeliveryData
{
    public List<string> DeliveryAreas { get; set; }
    // 用Dictionary接收动态键的对象,泛型T根据实际值类型调整(比如int、自定义类等)
    public Dictionary<string, int> EntryPerArea { get; set; }
}

2. 结合Restclient.Net与Newtonsoft.Json反序列化

Restclient.Net默认可能用System.Text.Json,你需要配置使用Newtonsoft作为序列化器:

// 初始化RestClient时指定Newtonsoft序列化适配器
var client = new RestClient(new NewtonsoftSerializationAdapter(), new Uri("你的API地址"));

// 发送请求并反序列化为自定义类
var response = await client.GetAsync<DeliveryData>();
var deliveryData = response.Body;

// 遍历访问动态键值
foreach (var area in deliveryData.DeliveryAreas)
{
    if (deliveryData.EntryPerArea.TryGetValue(area, out var entryCount))
    {
        Console.WriteLine($"区域{area}的条目数:{entryCount}");
    }
}

3. 注意事项

  • 如果entryPerArea的值是复杂对象而非基本类型,只需将Dictionary的泛型T替换为对应的自定义类即可,比如Dictionary<string, AreaEntry>
  • 确保已安装RestClient.Net.NewtonsoftJson NuGet包,否则无法使用NewtonsoftSerializationAdapter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:05:59