Search code examples
c#jsonasp.net-mvc-5json.net

How can I change the value of a JSON property using Json.NET?


I would like to modify the values AREA1 & AREA2 from the parsed JObject of the below JSON string.

How can I retrieve the elements with jObject.SelectTokens() and edit it them?

{
   "summary":{
      "summaryDataTable":{
         "id":"summaryDataTable",
         "type":"dataTable",
         "source":"/SmartScreen/SummaryFw",
         "columns":[
            {
               "name":"CreateDate",
               "title":"AREA1",
               "filterable":false
            },
            {
               "name":"CreateUser",
               "title":"AREA2",
               "filterable":false
            }
         ],
         "options":{
            "showFilter":false
         }
      }
   }
}

Solution

  • If you just need to modify it for the above JSON model, use JObject.SelectToken to get the parent objects using the JSON path & then set the value like below:

    var data = JObject.Parse(json);
    
    var firstColumn = data.SelectToken("summary.summaryDataTable.columns[0]");
    var secondColumn = data.SelectToken("summary.summaryDataTable.columns[1]");
    firstColumn["title"] = "replacedTitle1";
    secondColumn["title"] = "replacedTitle2";
    

    Output:

    {
      "summary": {
        "summaryDataTable": {
          "id": "summaryDataTable",
          "type": "dataTable",
          "source": "/SmartScreen/SummaryFw",
          "columns": [
            {
              "name": "CreateDate",
              "title": "replacedTitle1",
              "filterable": false
            },
            {
              "name": "CreateUser",
              "title": "replacedTitle2",
              "filterable": false
            }
          ],
          "options": {
            "showFilter": false
          }
        }
      }
    }