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

C#遍历JSON对象遇RuntimeBinderException错误求助

解决遍历JSON对象时遇到的RuntimeBinderException错误

你遇到的这个RuntimeBinderException是因为遍历mylist.buttons的方式不对——当你用dynamic反序列化JSON里的buttons对象后,它本质是Newtonsoft.Json里的JObject类型,直接foreach遍历它的话,拿到的每一项是JProperty(键值对的“键”部分),而不是你要的按钮对象本身,所以访问item.shortcut才会报错说JProperty没有这个定义。

快速修复代码

最简单的修改方式就是在遍历的时候访问JProperty的Value属性,这个才是对应按钮的对象:

int i = 1;
foreach (dynamic item in mylist.buttons)
{
    // 访问JProperty的Value属性获取按钮对象
    kc[i] = (Keys)Enum.Parse(typeof(Keys), (string)item.Value.shortcut);
    i++;
}

或者更直接一点,直接遍历buttons的Values集合,这样拿到的就是按钮对象本身,代码更清晰:

int i = 1;
foreach (dynamic button in mylist.buttons.Values)
{
    kc[i] = (Keys)Enum.Parse(typeof(Keys), (string)button.shortcut);
    i++;
}

更稳妥的类型安全方案

用dynamic虽然灵活,但很容易出现这类绑定错误,推荐你定义对应的实体类来反序列化JSON,这样编译期就能发现问题:

先定义匹配JSON结构的类:

public class AppSettings
{
    public int buttonByColumn { get; set; }
    public int buttonByLine { get; set; }
    public int iconSize { get; set; }
    public int settingsbutton { get; set; }
    public string settingsshortcut { get; set; }
    public Dictionary<string, ButtonConfig> buttons { get; set; }
}

public class ButtonConfig
{
    public string name { get; set; }
    public string type { get; set; }
    public string path { get; set; }
    public string shortcut { get; set; }
    public string iconPath { get; set; }
}

然后反序列化时指定类型:

var mylist = JsonConvert.DeserializeObject<AppSettings>(fileText);
kc = new Keys[mylist.buttonByColumn * mylist.buttonByLine];
kc[0] = (Keys)Enum.Parse(typeof(Keys), mylist.settingsshortcut);

int i = 1;
foreach (var button in mylist.buttons.Values)
{
    kc[i] = (Keys)Enum.Parse(typeof(Keys), button.shortcut);
    i++;
}

这样不仅避免了动态类型的绑定问题,代码可读性和维护性也更好。

内容的提问来源于stack exchange,提问作者Clément

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:27:36