Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With System.Text.Json, is there a way to EXCLUDE properties from a BASE class from serialization?

For example, I have a class that derives from ObservableValidator and my resulting serialization then includes HasErrors. I want to only include my derived class's properties and don't have access to modify the base class. Is there a way to do this?

public class Derived: ObservableValidator {

    [Required]
    [JsonPropertyName("name")] 
    [ObservableProperty]
    private string? _name;

}

serialized json:

 {
  "name": "Test",
  "HasErrors": false
}

How can I make name the only property written to my json?

NewtonSoft has what I want with this decorator, but haven't found an equivalent in System.Text.Json.

[JsonObject(MemberSerialization.OptIn)]
public class File

Could be related to similar issue, I have in addition to this one in which the MVVM generator doesn't propagate the [JsonIgnore]. Maybe need to refactor with non-observable record type class. Is there any other way of ignoring a property during JSON serialization instead of using [JsonIgnore] decorator?

like image 539
azulBonnet Avatar asked Oct 24 '25 06:10

azulBonnet


1 Answers

There's an open issue about this. Voting up there might speed up the fix.

As a work around, you can use a custom type info resolver:

public sealed class IgnoreHasErrorsTypeResolver : DefaultJsonTypeInfoResolver
{
    public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
    {
        JsonTypeInfo jsonTypeInfo = base.GetTypeInfo(type, options);

        if (jsonTypeInfo
            .Properties
            .FirstOrDefault(property => property.Name is nameof(ObservableValidator.HasErrors)) is JsonPropertyInfo hasErrorsJsonPropertyInfo)
        {
            jsonTypeInfo.Properties.Remove(hasErrorsJsonPropertyInfo);
        }

        return jsonTypeInfo;
    }
}

and use it like:

JsonSerializerOptions options = new()
{
    TypeInfoResolver = new IgnoreHasErrorsTypeResolver(),
};

string jsonText = JsonSerializer.Serialize(someObject, options);
like image 124
Andrew KeepCoding Avatar answered Oct 26 '25 20:10

Andrew KeepCoding