我试图反序列化这个Json代码:
"hotkeyOptions": {
"autoSwitchHotkeyPreset": true,
"currentHotkeySetName": "Paladin",
"hotkeySets": {
"Newbie": {
"F10": {
"useObject": 5645,
"useType": "SelectUseTarget"
},
"F11": {
"useObject": 5456,
"useType": "SelectUseTarget"
},
"F12": {
"useObject": 7565,
"useType": "Use"
},
"F8": {
"useObject": 7547,
"useType": "UseOnYourself"
},
"F9": {
"useObject": 4214,
"useType": "SelectUseTarget"
}
},
"Mega Mage": {
"Ctrl+F1": {
"chatText": "heal friend",
"sendAutomatically": true
},
"Ctrl+F4": {
"chatText": "mega haste",
"sendAutomatically": true
},
"F1": {
"chatText": "haste",
"sendAutomatically": true
},
"F10": {
"useObject": 3412,
"useType": "SelectUseTarget"
},
"F11": {
"useObject": 5343,
"useType": "SelectUseTarget"
},
},
"Paladin": {
"F1": {
"useObject": 4643,
"useType": "UseOnYourself"
},
"F2": {
"useObject": 6433,
"useType": "UseOnYourself"
},
"F3": {
"chatText": "haste",
"sendAutomatically": true
},
"F5": {
"chatText": "heal",
"sendAutomatically": true
}
},
"Mage": {
"F1": {
"chatText": "explosion",
"sendAutomatically": true
},
"F12": {
"useObject": 3003,
"useType": "SelectUseTarget"
}
},
"Knight": {
"Ctrl+F1": {
"chatText": "poke go",
"sendAutomatically": true
},
"F1": {
"chatText": "haste",
"sendAutomatically": true
},
}
}
}
我在尝试阅读其属性和值时遇到问题,但我无法获得名称属性,例如" Newbie"," Mega Mage", " Paladin"等
这就是我现在所得到的:
JToken token = JObject.Parse(json);
JToken hotkeyConfig = token.SelectToken("hotkeyOptions");
JToken activeHotkey = hotkeyConfig.SelectToken("currentHotkeySetName");
this.ActiveHotkeySet = activeHotkey.Value<string>(); //This is working, returning the "Paladin" string
JToken hotkeysSet = hotkeyConfig.SelectToken("hotkeySets");
foreach (var set in hotkeysSet.Children()) {
foreach (JObject obj in set.Children<JObject>()) {
foreach(JProperty prop in obj.Properties()) {
var teste = prop.Name;
}
}
}
使用上面的代码我可以到达键盘快捷键,如&#34; F10&#34;,&#34; Ctrl + F1&#34;,但无法获得&#34; Parent命名&#34; (新手)。
有一种简单的方法可以阅读这种JSON结构吗?
答案 0 :(得分:2)
您可以使用Newtonsoft。而且我更喜欢将json解析为类。解决问题的示例:
首先定义反序列化的类:
public class Hotkeys
{
[JsonProperty("hotkeyOptions")]
public HotkeyOptions HotkeyOptions { get; set; }
}
public class HotkeyOptions
{
[JsonProperty("autoSwitchHotkeyPreset")]
public bool AutoSwitchHotkeyPreset { get; set; }
[JsonProperty("currentHotkeySetName")]
public string CurrentHotkeySetName { get; set; }
[JsonProperty("hotkeySets")]
public Dictionary<string, JObject> HotkeySets { get; set; }
}
然后你可以这样读:
var hotkeys = JsonConvert.DeserializeObject<Hotkeys>(json);
foreach(var hotkeySet in hotkeys.HotkeyOptions.HotkeySets)
{
string hotkeySetName = hotkeySet.Key; // "Newbie" etc..
foreach(var hotkey in hotkeySet.Value)
{
string hotkeyString = hotkey.Key; // "F10" etc..
}
}