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

C# 如何访问模型中的LookupValue属性并实现正确JSON序列化

问题根因

你定义的CreateNewLookup类中,LookupValues属性为集合类型(如List<LookupValue>、LookupValue[]等),但你当前的初始化代码直接给该属性赋值了单个LookupValue实例,不符合类型约束,因此无法正常访问集合内元素的属性,也不符合目标JSON的数组结构要求。

解决方法

1. 修改对象初始化代码

将LookupValues属性赋值为集合类型,示例如下:

private static CreateNewLookup DefaultNewLookuptRecord => new CreateNewLookup()
{
    Reference = "TestRef",
    Label = "City",
    LookupValues = new List<LookupValue> // 改为集合初始化,若为数组类型则替换为new LookupValue[]
    {
        new LookupValue
        {
            Tenant = "9",
            Label = "London",
            Value = "London",
            IsActive = true,
        }
        // 如有多个LookupValue可继续在大括号内追加
    }
};

2. 访问属性的写法

  • 访问集合内第一个元素的属性:
    var firstLabel = DefaultNewLookuptRecord.LookupValues.First().Label;
  • 遍历所有元素访问属性:
foreach (var item in DefaultNewLookuptRecord.LookupValues)
{
    var tenant = item.Tenant;
    // 其他属性访问逻辑
}

修改完成后直接序列化即可生成你需要的目标JSON格式,不需要额外调整序列化逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:18:00