[英]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.