CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.99k stars 294 forks source link

[MVVM] Cannot suppress [RelayCommand] from JsonSerializer.Deserlialize with [JsonIgnore] #793

Closed stephenquan closed 10 months ago

stephenquan commented 10 months ago

Describe the bug

I am using CommunityToolkit.Mvvm 8.2.2. I have the following ViewModel which I want to serialize to Json, but, unfortunately, the unwanted [RelayCommand] is appearing as well:

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Json))]
    private Int64 _acc = 0;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Json))]
    public Int64 _accPower = 1;

    [RelayCommand]
    private Task IncAcc()
    {
        Acc++;
        AccPower = AccPower * 2;
        return Task.CompletedTask;
    }

    [JsonIgnore]
    public string Json
    {
        get
        {
            try
            {
                return JsonSerializer.Serialize(this);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

The value being returned by Json property is:

{"Acc":0,"AccPower":1,"IncAccCommand":{"ExecutionTask":null,"CanBeCanceled":false,"IsCancellationRequested":false,"IsRunning":false}}

The desired Json property is:

{"Acc":0,"AccPower":1}

Regression

No response

Steps to reproduce

I'm using the ViewModel in a Maui application with the following XAML:

<VerticalStackLayout>
    <Label Text="{Binding Acc, StringFormat='Acc: {0}'}" />
    <Label Text="{Binding AccPower, StringFormat='AccPower: {0}'}" />
    <Label Text="{Binding Json, StringFormat='Json: {0}'}" />
    <Button Text="Click me" Command="{Binding IncAccCommand}"/>
</VerticalStackLayout>

Expected behavior

I would like the Label that shows the Json property to show:

Json: {"Acc":0,"AccPower":1}

Screenshots

No response

IDE and version

VS 2022

IDE version

Visual Studio 17.7.4

Nuget packages

Nuget package version(s)

CommunityToolkit.Mvvm 8.2.2

Additional context

No response

Help us help you

Yes, but only if others can assist

Sergio0694 commented 10 months ago

Add [property: JsonIgnore] on the IncAcc method 🙂

Support was introduced in https://github.com/CommunityToolkit/dotnet/pull/630.