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

动态访问JSON对象触发Microsoft.CSharp.Runtime.RuntimeBinderException异常

解决Jira API响应访问异常的方案

问题原因

你用JsonSerializer.Deserialize<dynamic>得到的对象本质是JsonElement,它的索引器仅支持整数下标(用于数组),直接用字符串["issues"]访问属性会触发运行时绑定错误,因为编译器无法识别字符串索引的正确调用方式。

方案一:使用JsonElement的GetProperty方法

直接将反序列化结果指定为JsonElement,通过GetProperty获取目标字段:

// 替换原反序列化和输出代码
JsonElement jsonObject = JsonSerializer.Deserialize<JsonElement>(result);
JsonElement issuesElement = jsonObject.GetProperty("issues");
Console.WriteLine(issuesElement.ToString());

方案二:定义强类型模型(推荐,便于后续提取字段)

创建对应Jira响应结构的类,反序列化后直接通过属性访问,更安全且易维护:

// 定义模型类
public class JiraSearchResponse
{
    [JsonPropertyName("expand")]
    public string Expand { get; set; }
    [JsonPropertyName("startAt")]
    public int StartAt { get; set; }
    [JsonPropertyName("maxResults")]
    public int MaxResults { get; set; }
    [JsonPropertyName("total")]
    public int Total { get; set; }
    [JsonPropertyName("issues")]
    public List<JiraIssue> Issues { get; set; }
}

public class JiraIssue
{
    [JsonPropertyName("key")]
    public string Key { get; set; }
    [JsonPropertyName("fields")]
    public JiraIssueFields Fields { get; set; }
}

public class JiraIssueFields
{
    [JsonPropertyName("summary")]
    public string Summary { get; set; } // 问题标题
    [JsonPropertyName("creator")]
    public JiraUser Creator { get; set; } // 创建者
}

public class JiraUser
{
    [JsonPropertyName("displayName")]
    public string DisplayName { get; set; }
}

// 反序列化并访问字段
var jiraResponse = JsonSerializer.Deserialize<JiraSearchResponse>(result);
if (jiraResponse.Issues?.Count > 0)
{
    var latestIssue = jiraResponse.Issues[0];
    Console.WriteLine($"标题:{latestIssue.Fields.Summary}");
    Console.WriteLine($"创建者:{latestIssue.Fields.Creator.DisplayName}");
}

补充说明

  • 若需要处理更多Jira字段,可根据API返回的完整结构扩展模型类;
  • WebClient已被标记为过时,建议替换为HttpClient以获得更好的性能和异步支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:35:20