dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

ObservableValidator 'HasErrors' should be ignored from JSON serialization

Open FelixCCWork opened this issue 1 year ago • 0 comments

Describe the bug

When serializing classes inheriting from ObservableValidator using System.Text.Json the 'HasErrors' property also gets serialized. To ensure a clean JSON output, it would be beneficial to add the [JsonIgnore] attribute to the 'HasErrors' property. As this property has no state there shouldn't be any disadvantages having it ignored from serialization.

namespace CommunityToolkit.Mvvm.ComponentModel;

public abstract class ObservableValidator : ObservableObject, INotifyDataErrorInfo
{
    [JsonIgnore] <<< Added attribute
    [Display(AutoGenerateField = false)]
    public bool HasErrors => this.totalErrors > 0;
}

Regression

No response

Steps to reproduce

  1. Create a class inheriting from ObservableValidator
  2. Use System.Text.Json to serialize the class
  3. The 'HasErrors' property is included in the resulting JSON

Expected behavior

As this property has no state it should be ignored from serialization.

Workaround

There is a workaround using a custom DefaultJsonTypeInfoResolver to exclude the property from the serialization.

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

        JsonPropertyInfo? propToRemove = jsonTypeInfo.Properties.FirstOrDefault(prop => prop.Name is nameof(ObservableValidator.HasErrors));

        if (propToRemove is not null)
            jsonTypeInfo.Properties.Remove(propToRemove);

        return jsonTypeInfo;
    }
}

IDE and version

VS 2022

IDE version

No response

Nuget packages

  • [ ] CommunityToolkit.Common
  • [ ] CommunityToolkit.Diagnostics
  • [ ] CommunityToolkit.HighPerformance
  • [x] CommunityToolkit.Mvvm (aka MVVM Toolkit)

Nuget package version(s)

8.3.2

Additional context

No response

Help us help you

Yes, but only if others can assist

FelixCCWork avatar Dec 04 '24 08:12 FelixCCWork