Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having trouble updating JSON File in C#

I have a JSON File below content.

{
  "properties": {
    "workspaceId": "xxxx",
    "logs": [
      {
        "categoryGroup": "allLogs",
        "enabled": false,
        "retentionPolicy": {
          "enabled": false,
          "days": 0
        }
      }
    ],
    "logAnalyticsDestinationType": ""
  }
}

I am trying to change the value of the object workspaceId from "xxxx" to actual value from a string LAWorkspaceID. I am using below code but getting error

System.Private.CoreLib: Exception while executing function:
RAMP-VinnyLearn. Newtonsoft.Json: Accessed JObject values with invalid key value: 0. Object property name expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string LAWorkSpaceID = "NewValueForMyLAWorkspaceID";
string json = File.ReadAllText("DisableRequestBody.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["properties"][0]["workspaceId"] = LAWorkSpaceID;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("DisableRequestBody.json", output);

>Solution :

"properties" is an object and not array.

try to replace

jsonObj["properties"][0]["workspaceId"]

with

jsonObj["properties"]["workspaceId"]

and the output is

{
  "properties": {
    "workspaceId": "NewValueForMyLAWorkspaceID",
    "logs": [
      {
        "categoryGroup": "allLogs",
        "enabled": false,
        "retentionPolicy": {
          "enabled": false,
          "days": 0
        }
      }
    ],
    "logAnalyticsDestinationType": ""
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading