6

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.

theGhostN
  • 342
  • 7
  • 20
  • Why do you have _"using Json.Net"_ in the title if you want to use `System.Text.Json`? – Guru Stron Apr 24 '22 at 07:45
  • 1
    Why don't use want to use `newtonsoft.json` but tag it? – D-Shih Apr 24 '22 at 07:45
  • _"How do I remove a property from a Json string with System.Text.Json ?"_ - by updating to .NET 6 and using new `JsonNode` API – Guru Stron Apr 24 '22 at 07:47
  • @GuruStron sorry I thought both are the same. I want to use System.Text.Json – theGhostN Apr 24 '22 at 07:47
  • @GuruStron Sorry I can not update to 6 . But if there is no way with 5 please provide an answer – theGhostN Apr 24 '22 at 07:48
  • 2
    You can make those additional properties go into an `extension data` property, without losing on roundtrip, see https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-handle-overflow – Anand Sowmithiran Apr 24 '22 at 11:09
  • 2
    You could store it as a `Dictionary` then simply remove the `Age` key – Charlieface Apr 24 '22 at 11:34
  • Your json is not valid. Post a valid json at first. "from a Json string with System.Text.Json" - what do you mean? Json object or just string? You can use using string.replace for a string. You don't need any serializer for this. – Serge Apr 24 '22 at 12:19
  • `JsonDocument` is read-only. Assuming you don't know your JSON structure in advance and can't deserialize to some typed data model, see [Modifying a JSON file using System.Text.Json](https://stackoverflow.com/q/58997718/3744182) for options and workarounds. – dbc Apr 24 '22 at 13:13
  • @Serge There are obviously many ways to transform JSON. Unless you have a trivial use case, string manipulation is potentially error-prone. It is almost always better to deserialize, process, and serialize again. – Stephan Schlecht Apr 25 '22 at 08:05
  • @StephanSchlecht What I meant that json is not valid since it has c# tag and can not be a javascript object – Serge Apr 25 '22 at 10:07

1 Answers1

3

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)); 
James Risner
  • 5,451
  • 11
  • 25
  • 47