-1

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
  • 163
  • 6
  • 17
  • 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://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-handle-overflow – Anand Sowmithiran Apr 24 '22 at 11:09
  • 1
    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

-1

One possible way would be to first deserialize the data into an object. Then it is easy to filter in the code. Then just set any property you don't want to see in the output to null. With IgnoreNullValues of the JsonSerializerOptions, you could then serialize and the null properties would be just omitted.

In a self-contained complete example, this would look something like this:

#nullable enable
using System;
using System.Text.Json;

namespace JsonRemoveProp
{
    internal class Person
    {
        public string? Name { get; set; }
        public int? Age { get; set; }
        public string? Location { get; set; }

        public override string ToString()
        {
            return $"{nameof(Name)}: {Name}, {nameof(Age)}: {Age}, {nameof(Location)}: {Location}";
        }
    }


    class Program
    {
        private const String JsonString1 = @"{
                ""Name"": ""Mike"",
                ""Age"" : 12,
                ""Location"" : ""Africa""
            }";

        private const String JsonString2 = @"{
                ""Name"": ""Tom"",
                ""Age"" : 12,
                ""Location"" : ""Africa""
            }";

        static void Main()
        {
            Console.WriteLine(".NET Version: {0}", Environment.Version);

            var person = JsonSerializer.Deserialize<Person>(JsonString1);
            var newJsonString = Filter(person, "Mike", false);
            Console.WriteLine(newJsonString);
            
            person = JsonSerializer.Deserialize<Person>(JsonString2);
            newJsonString = Filter(person, "Mike", true);
            Console.WriteLine(newJsonString);
        }

        private static string? Filter(Person? person, string name, bool removeAge)
        {
            if (person == null) return null;
            if (person.Name == name) {
                person.Name = null;
            }
            if (removeAge)
            {
                person.Age = null;
            }
            JsonSerializerOptions options = new()
            {
                IgnoreNullValues = true
            };
            return JsonSerializer.Serialize(person, options);
        }
    }
}

Output would be:

.NET Version: 5.0.16
{"Age":12,"Location":"Africa"}
{"Name":"Tom","Location":"Africa"}
Stephan Schlecht
  • 22,583
  • 1
  • 26
  • 38