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

C#使用RestSharp反序列化JSON后无法为List类型属性info添加元素

问题原因

  • 你在代码中单独实例化了foo对象,所有元素添加操作都是作用在foo的info列表上,完全没有修改最终返回的result对象中data集合里的MyItem实例,所以返回结果的info列表始终是空的。
  • 你计算得到的total变量当前没有被使用,不影响核心逻辑但属于冗余代码。

修复方案

调整循环内的逻辑,直接给遍历到的每个item的info列表添加元素即可,修改后代码如下:

var client = new RestClient("XXX");
client.UseNewtonsoftJson();
var request = new RestRequest("XXX");
var response = client.Execute(request);

var result = JsonConvert.DeserializeObject<Root>(response.Content);
foreach (var item in result.data)
{
    var total = item.GetType()
        .GetProperties()
        .Select(x => x.GetValue(item, null))
        .Count(v => v is null || (v is string a && string.IsNullOrWhiteSpace(a)));

    // 直接操作当前遍历到的item的info列表
    item.info.Add(new Info() { status = "test" }); 
}
return Ok(result);

可选优化

你已经为RestSharp配置了Newtonsoft.Json序列化器,可以直接使用泛型执行方法省去手动反序列化步骤:

var result = client.Execute<Root>(request).Data;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:57:00