CommunityToolkit / CommunityToolkit/dotnet

ObservableValidator 'HasErrors' should be ignored from JSON serialization

Open
#1,012 1 comment 11 reactions 0 assignees View on GitHub
bug :bug:
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

### 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.

```csharp
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.
```csharp
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.