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

如何使用dynamic访问JSON中的嵌套对象、数组属性与顶层属性

使用dynamic访问嵌套JSON对象的值

获取顶层的TotalPrice

直接通过obj.TotalPrice访问即可,因为它是JSON的顶层属性:

dynamic obj = JsonConvert.DeserializeObject(response);
double totalPrice = obj.TotalPrice;

获取Order数组内的Price

Order是数组类型,需要先通过索引定位到数组中的具体元素(示例里是第一个元素,索引为0),再访问其Price属性:

// 获取数组第一个Order项的Price
double orderPrice = obj.Order[0].Price;

完整示例代码

string response = @"
{
    ""Order"": [
        {
            ""Number"": ""1"",
            ""Price"": 1.99
        }
    ],
    ""TotalPrice"": 1.99
}";

dynamic obj = JsonConvert.DeserializeObject(response);

// 读取顶层TotalPrice
double totalPrice = obj.TotalPrice;
// 读取Order数组第一个元素的Price
double orderPrice = obj.Order[0].Price;

Console.WriteLine($"TotalPrice: {totalPrice}");
Console.WriteLine($"Order Price: {orderPrice}");

如果Order数组包含多个元素,可以通过循环遍历所有项的Price:

foreach (dynamic orderItem in obj.Order)
{
    double price = orderItem.Price;
    Console.WriteLine($"Order {orderItem.Number} 的价格: {price}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:01:14