12

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.

11
  • Why do you have "using Json.Net" in the title if you want to use System.Text.Json? Commented Apr 24, 2022 at 7:45
  • 1
    Why don't use want to use newtonsoft.json but tag it? Commented Apr 24, 2022 at 7:45
  • 1
    "How do I remove a property from a Json string with System.Text.Json ?" - by updating to .NET 6 and using new JsonNode API Commented Apr 24, 2022 at 7:47
  • 2
    You can make those additional properties go into an extension data property, without losing on roundtrip, see learn.microsoft.com/en-us/dotnet/standard/serialization/… Commented Apr 24, 2022 at 11:09
  • 2
    You could store it as a Dictionary<string, object> then simply remove the Age key Commented Apr 24, 2022 at 11:34

1 Answer 1

6

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)); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.