Search code examples
c#json.net

C# Remove object from JSON with nested property


I have this JSON, and I want to delete "delta" section with all nested property. I already use JObject.Remove("delta") but I have this error:

Cannot add or remove items from Newtonsoft.Json.Linq.JProperty

JSON

{
  "state": {
    "desired": {
      "optionals": {
        "Variant": "XXXX",
        "Vehicle": {
          "COC00": "AAAA",
          "D0000": "BBBB",
          "D0600": "CCCC"
        }
      }
    },
    "delta": {
      "optionals": {
        "Variant": "XXXX",
        "Vehicle": {
          "COC00": "AAAA",
          "D0000": "BBBB",
          "D0600": "CCCC"
          "D2000": "DDDD",
        }
      }
    }
  },
  "timestamp": 1700154568
}

Solution

  • Use selectToken and then remove the property.

        JObject jo = JObject.Parse(json);
        JObject header = (JObject)jo.SelectToken("state");
        header.Property("delta").Remove();
        json = jo.ToString();