Skip to content

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

@stephenquan

Description

@stephenquan

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

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

Nuget package version(s)

CommunityToolkit.Mvvm 8.2.2

Additional context

No response

Help us help you

Yes, but only if others can assist

Metadata

Metadata

Assignees

No one assigned

    Labels

    mvvm-toolkit 🧰Issues/PRs for the MVVM Toolkitquestion ❔An issue just asking some question

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions