我有以下JSON:
{
"Sonos": [
{
"192.168.10.214": [
{
"Volume": "5",
"Extension": null,
"Name": "Wohnzimmer"
}
]
},
{
"192.168.10.204": [
{
"Volume": "5",
"Extension": null,
"Name": "Büro"
}
]
}
]
}
点击我要更改音量,我尝试使用此片段进行操作:
string[] address = ip.Text.Split(new string[] {" | "},
StringSplitOptions.RemoveEmptyEntries); //ip is a ListViewItem
...
dynamic jsonObj = JsonConvert.DeserializeObject(config);
jsonObj["Sonos"][address[0]]["Volume"] = "10";
现在最后一行抛出
使用无效键值访问JArray值:" 192.168.10.214"。预期Int32数组索引。
如何更新指定IP的卷?我是using Newtonsoft.Json;
任何暗示都表示赞赏!
修改
根据要求提供全功能:
private void IncomingCall()
{
int i = 0;
foreach (ListViewItem ip in sonosListExt1.Items)
{
string[] address = ip.Text.Split(new string[] {" | "}, StringSplitOptions.RemoveEmptyEntries);
/* Get current Volume and save */
string getVol = sendXML("/MediaRenderer/RenderingControl/Control", "GetVolume",
"urn:schemas-upnp-org:service:RenderingControl:1",
"<InstanceID>0</InstanceID><Channel>Master</Channel>", address[0]);
XmlDocument xmlResponse = new XmlDocument();
xmlResponse.LoadXml(getVol);
var curVol = ((XmlElement) xmlResponse.FirstChild.FirstChild.FirstChild).InnerText;
string config = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\config.json");
dynamic jsonObj = JsonConvert.DeserializeObject(config);
jsonObj["Sonos"][i][address[0]][i]["Volume"] = curVol;
string output = JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "cfg\\config.json", output);
/* Lower Volume */
sendXML("/MediaRenderer/RenderingControl/Control", "SetVolume",
"urn:schemas-upnp-org:service:RenderingControl:1",
"<InstanceID>0</InstanceID><Channel>Master</Channel><DesiredVolume>2</DesiredVolume>", address[0]);
/* Var up */
i++;
}
}
答案 0 :(得分:2)
"Sonos"
是一个数组,子项及其值也是如此。
所以访问如下:
jsonObj["Sonos"][0][address[0]][0]["Volume"] = "10";
修改强>
对于foreach
迭代,请考虑与此类似的东西(hacky但是如果结构得到保证那么这应该起作用耸肩):
foreach (ListViewItem ip in sonosListExt1.Items)
{
var index = sonosListExt1.Items.ToList().IndexOf(ip);
string[] address = ip.Text.Split(new string[] {" | "}, StringSplitOptions.RemoveEmptyEntries);
/* --- Excluded XML manipulation code --- */
jsonObj["Sonos"][index][address[0]][0]["Volume"] = "10";
}
理想情况下,您应该将Sonos
更改为JSON字典,并将地址值作为键。