Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically remove property from JSON using System.Text.Json

Note 1 : I do NOT want to use newtonsoft.json !

Note 2 : This is not a duplicate, other answers use newtonsoft.json !

Note 3 : using .Net 5.

How do I remove a property from a Json string with System.Text.Json ?

{
 Name: "Mike",
 Age : 12,
 Location : "Africa"
}

I want to be able to remove based on both property name and value. For example remove Age property or remove persons with the name Mike.

like image 265
theGhostN Avatar asked Mar 17 '26 06:03

theGhostN


1 Answers

I hope the below solution might help to remove the property.
emp is your object

var jsonObject = System.Text.Json.Nodes.JsonNode.Parse(emp.ToJson()).AsObject();

Remove the property
Age is the property of emp

jsonObject.Remove(nameof(emp.Age)); 
like image 182
Mahantesh Kendhuli Avatar answered Mar 18 '26 20:03

Mahantesh Kendhuli