How to remove property from json object in c#

To remove a property from a JSON object in C#, you can use the Newtonsoft.Json library (also known as JSON.NET) which provides flexible JSON support. Follow the steps below to remove a property from a JSON object:

  1. Install the Newtonsoft.Json package from NuGet if you haven’t already.
  2. Deserialize the JSON string into a dynamic object or JObject:

    
    string jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
    dynamic jsonObject = JsonConvert.DeserializeObject(jsonString); // or JObject.Parse(jsonString);
                
  3. Remove the property from the dynamic object or JObject:

    • If you are using a dynamic object:

      
      // Assuming property name to be removed is "age"
      jsonObject.age = null;
                          
    • If you are using a JObject:

      
      // Assuming property name to be removed is "age"
      jsonObject.Remove("age");
                          
  4. Serialize the modified object back to JSON string:

    
    string modifiedJsonString = JsonConvert.SerializeObject(jsonObject);
                

Here’s a complete example:


using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        // Deserialize JSON string into dynamic object
        dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);

        // Remove the "age" property
        jsonObject.age = null;

        // Serialize modified object back to JSON string
        string modifiedJsonString = JsonConvert.SerializeObject(jsonObject);

        Console.WriteLine(modifiedJsonString);
    }
}
    

In the above example, the “age” property is removed from the JSON object represented by the jsonString, and the modified JSON string is printed to the console.

Leave a comment