Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ObservableValidator 'HasErrors' should be ignored from JSON serialization #1012

Open
1 of 4 tasks
FelixCCWork opened this issue Dec 4, 2024 · 0 comments
Open
1 of 4 tasks
Labels
bug 🐛 An unexpected issue that highlights incorrect behavior

Comments

@FelixCCWork
Copy link

FelixCCWork commented Dec 4, 2024

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
  • 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 FelixCCWork added the bug 🐛 An unexpected issue that highlights incorrect behavior label Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug 🐛 An unexpected issue that highlights incorrect behavior
Projects
None yet
Development

No branches or pull requests

1 participant