[英]foreach loop on json array c#
我在foreach
循環中遇到錯誤,但我不明白為什么。 你能幫助我嗎?
這對我來說是一個小項目。
json:
{
"buttonByColumn": 1,
"buttonByLine": 1,
"iconSize": 100,
"settingsbutton": 1,
"settingsshortcut": "Escape",
"buttons": {
"button1": {
"name": "test",
"type": "",
"path": "",
"shortcut": "E",
"iconPath": ""
}
}
}
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++;
}
錯誤:
$ exception {“'Newtonsoft.Json.Linq.JProperty'不包含對'shortcut'的任何定義。}} Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
在您的JSON中, buttons
不是數組。 它是一個對象。 因此,您的foreach
循環實際上是遍歷buttons
對象的屬性 ,其中第一個(也是唯一的)屬性是button1
。 shortcut
位於button1
對象內部; 它不是直接位於buttons
內部,所以這就是為什么您會遇到錯誤。 由於item
實際上是一個JProperty
,因此您需要使用Value
訪問器來訪問shortcut
。
嘗試像這樣:
kc[i] = (Keys)Enum.Parse(typeof(Keys), (string)item.Value.shortcut);
還要注意,您的kc
數組的大小可能不夠大:您在settingsshortcut
中使用了額外的元素。 因此,您可能需要為此添加一個帳戶。
小提琴: https : //dotnetfiddle.net/9DZxwc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.