修改JSON格式的值

本文关键字:格式 JSON 修改 | 更新日期: 2023-09-27 18:17:09

我有以下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值中key值无效:"192.168.10.214"。

如何更新指定IP的Volume ?我是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++;
            }
        }

修改JSON格式的值

"Sonos"是一个数组,子项及其值也是一个数组。

所以访问如下:

jsonObj["Sonos"][0][address[0]][0]["Volume"] = "10";
编辑:

对于foreach迭代,考虑类似于这样的东西(有点粗糙,但如果结构得到保证,那么这应该可以工作耸肩):

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字典。