简体   繁体   English

JSON数组C#上的foreach循环

[英]foreach loop on json array c#

I have en error in a foreach loop and I don't understand why. 我在foreach循环中遇到错误,但我不明白为什么。 Can you help me? 你能帮助我吗?

this is for a small project for me. 这对我来说是一个小项目。

json: json:

{
    "buttonByColumn": 1,
    "buttonByLine": 1,
    "iconSize": 100,
    "settingsbutton": 1,
    "settingsshortcut": "Escape",
    "buttons": {
        "button1": {
            "name": "test",
            "type": "",
            "path": "",
            "shortcut": "E",
            "iconPath": ""
        }
    }
}

c#: C#:

public Keys[] kc;

dynamic mylist = JsonConvert.DeserializeObject(fileText);
kc = new Keys[buttonByColumn * buttonByLine];
kc[0] = (Keys)Enum.Parse(typeof(Keys), (string)mylist.settingsshortcut);

int i = 1;
foreach (dynamic item in mylist.buttons)
{
    kc[i] = (Keys)Enum.Parse(typeof(Keys), (string)item.shortcut);//error is here
    i++;
}

error: 错误:

$exception {"'Newtonsoft.Json.Linq.JProperty' does not contain any definition for 'shortcut'"} Microsoft.CSharp.RuntimeBinder.RuntimeBinderException $ exception {“'Newtonsoft.Json.Linq.JProperty'不包含对'shortcut'的任何定义。}} Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

In your JSON, buttons is not an array; 在您的JSON中, buttons不是数组。 it is an object. 它是一个对象。 So your foreach loop is actually iterating over the properties of the buttons object, of which the first (and only) property is button1 . 因此,您的foreach循环实际上是遍历buttons对象的属性 ,其中第一个(也是唯一的)属性是button1 shortcut is inside the button1 object; shortcut位于button1对象内部; it is not directly inside buttons , so that is why you are getting an error. 它不是直接位于buttons内部,所以这就是为什么您会遇到错误。 Since item is actually a JProperty under the covers, you need to use the Value accessor to get down to the shortcut . 由于item实际上是一个JProperty ,因此您需要使用Value访问器来访问shortcut

Try like this instead: 尝试像这样:

kc[i] = (Keys)Enum.Parse(typeof(Keys), (string)item.Value.shortcut);

Also note that your kc array may not be sized large enough: you are using an extra element for the settingsshortcut . 还要注意,您的kc数组的大小可能不够大:您在settingsshortcut中使用了额外的元素。 So you probably need to add one to account for that. 因此,您可能需要为此添加一个帐户。

Fiddle: https://dotnetfiddle.net/9DZxwc 小提琴: https : //dotnetfiddle.net/9DZxwc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM