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"}