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

使用Json.NET反序列化JSON字符串时属性始终为null的问题

排查JSON反序列化后id为null的问题

我来帮你梳理下这个问题,你遇到的id始终返回null的情况,大概率是JSON结构和C#类不匹配或者序列化配置细节没处理好,下面是几个常见的排查和解决方向:

1. 接口返回的是数组,你却用单个对象接收

你提到接口会返回多项数据,那返回的JSON很可能是数组格式(比如 [{"id":"123"},{"id":"456"}]),但你现在用单个Company类去反序列化,这种情况下序列化器无法把数组转成单个对象,自然拿不到id值。

解决方法是用集合类接收:

List<Company> companyList = JsonConvert.DeserializeObject<List<Company>>(companyResponse.Content);

2. JSON字段和类属性的大小写不匹配

Newtonsoft.Json默认是区分大小写的,如果接口返回的JSON里id字段是"Id"(首字母大写),但你的类里定义的是小写的id,两者无法映射,就会导致id为null。

你可以选两种方式解决:

  • 把类的属性改成和JSON一致的大小写:
    public class Company { public string Id { get; set; } }
    
  • 或者用JsonProperty特性强制指定映射的字段名:
    public class Company 
    { 
        [JsonProperty("Id")] // 这里填JSON里实际的字段名
        public string id { get; set; } 
    }
    

3. id字段嵌套在JSON的子对象里

有些接口返回的JSON结构会把数据包裹在子节点里,比如:

{
  "result": [
    {"id": "123"},
    {"id": "456"}
  ]
}

这种情况下你需要定义一个包含子节点的父类来接收:

public class CompanyResponse
{
    public List<Company> result { get; set; }
}

public class Company { public string id { get; set; } }

然后反序列化到父类:

CompanyResponse response = JsonConvert.DeserializeObject<CompanyResponse>(companyResponse.Content);
List<Company> companyList = response.result;

最后建议你先把companyResponse.Content打印出来,看看实际返回的JSON结构到底是什么样的,这是最快定位问题的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:26:39