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

在C#中从JSON响应获取id值遇null问题求助

如何从嵌套JSON中正确获取"id"字段值?

给定的JSON响应:

"{\"items\":[{\"libId\":\"gc1373wgw1mamn8baegfg2q2tsw4lnv1\",\"id\":\"bya51p40751d6oh0e653d5j645st5abk\",\"createdAt\":\"2023-08-10T13:06:05.985Z\",\"createdBy\":\"f393281c-265e-4116-95fd-804e2c10ef5a\",\"modifiedAt\":\"2023-08-14T12:53:29.645Z\",\"modifiedBy\":\"f393281c-265e-4116-95fd-804e2c10ef5a\",\"v\":2,\"name\":\"Steel Status\",\"schema\":{\"v\":1,\"props\":{\"prop_7jf006f02m19eilzpql7hziuonnajtaj\":{\"type\":\"boolean\",\"required\":true,\"default\":false},\"prop_cvelncsngupkcsczuwpbzpb8wvckvmo9\":{\"type\":\"boolean\",\"required\":true,\"default\":false}}},\"i18n\":{\"__definition-sort-order__\":{\"name\":\"__definition-sort-order__\",\"props\":{\"__definition-sort-order__\":\"0\"}},\"en-US\":{\"name\":\"Steel Status\",\"props\":{\"prop_7jf006f02m19eilzpql7hziuonnajtaj\":\"fabrication\",\"prop_cvelncsngupkcsczuwpbzpb8wvckvmo9\":\"Erection\"}},\"__prop-order__\":{\"name\":\"__prop-order__\",\"props\":{\"prop_7jf006f02m19eilzpql7hziuonnajtaj\":\"0\",\"prop_cvelncsngupkcsczuwpbzpb8wvckvmo9\":\"1\"}}},\"_actions\":[\"pset:GetDefVersionSchema\",\"pset:GetDefVersion\",\"pset:GetDefVersions\",\"pset:GetDef\",\"pset:UpdateDef\",\"pset:ValidatePSets\",\"pset:Subscribe\",\"pset:GetPSet\",\"pset:ListPSets\",\"pset:PutPSet\"]}]}"

之前尝试的错误代码(返回null):

JObject obj = JObject.Parse(responseBody);
string id = (string)obj["id"];
var datas = (JObject)JsonConvert.DeserializeObject(responseBody);
string nodid = datas["id"].Value<string>();

问题原因:

你的JSON结构中,id字段并不在根节点,而是嵌套在items数组的第一个元素对象里。直接从根节点取id自然会返回null。

正确的获取方法:

方法1:使用JObject直接解析层级

JObject obj = JObject.Parse(responseBody);
// 先定位到items数组,再取第一个元素,最后获取id字段
string id = obj["items"][0]["id"].ToString();

方法2:反序列化为强类型类(更规范)

先定义对应JSON结构的类:

public class Item
{
    public string id { get; set; }
    // 如果需要其他字段,可以按需添加,比如libId、name等
}

public class Root
{
    public List<Item> items { get; set; }
}

然后反序列化并获取id:

Root root = JsonConvert.DeserializeObject<Root>(responseBody);
string id = root.items[0].id;

两种方法都能正确获取到id值:bya51p40751d6oh0e653d5j645st5abk

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:57:47