Search code examples
c#jsonjson.net

Edit JSON file in C#


I am trying to edit a JSON file to append a value. However, I can't find a way to get the expected result. Given the below JSON:

{
   "First": "1",
   "Second": "2",
   "A_lot": [
      { 
         "Address":"Str" 
      },
      { 
         "Fruits" : [ "apple", "orange" ],
         "colors": : [] 
      }
   ], 
   "last": "end 
}

I want to add a fruit called banana and my JSON to look

{
   "First": "1",
   "Second": "2",
   "A_lot": [
      { 
         "Address":"Str" 
      },
      { 
         "Fruits" : [ "apple", "orange", "banana" ],
         "colors:" : [] 
      }
   ], 
   "last": "end 
}

I have search online but I couldn't find anything related. When I am trying to run this:

 var myjson = File.ReadAllText(pathtojson);
 JObject newDeploymentProfileDocument = JObject.Parse(myjson);

 var deploymentProperties = newDeploymentProfileDocument["A_lot"][1];

 var myFruit = "banana";
 deploymentProperties["Fruits"].AddAfterSelf(myFruit);

 File.WriteAllText(myjson, newDeploymentProfileDocument.ToString());

I am getting the following error:

Newtonsoft.Json.JsonException: 'Newtonsoft.Json.Linq.JProperty cannot have multiple values.

Since I am new to C#, let alone C# and json files, can you please point me what I am missing? Thanks in advance


Solution

  • Your sent JSON seems is not the correct format. If you mean something like this:

    {
      "First": "1",
      "Second": "2",
      "A_lot": [
        {
          "Address": "Str",
          "Fruits": [ "apple", "orange" ],
          "colors": []
        }
      ],
      "last": "end"
    }
    

    As the others mentioned in comments, just do it like this:

        ...
        var deploymentProperties = (JArray)newDeploymentProfileDocument["A_lot"][0]["Fruits"];
        var myFruit = "banana";
        deploymentProperties.Add(myFruit);
        ...
    

    Edited

    If you don't want to change your JSON structure, you can use this:

    var deploymentProperties = (JArray)newDeploymentProfileDocument["A_lot"][1]["Fruits"];
    var myFruit = "banana";
    deploymentProperties.Add(myFruit);