0

Is there an "easy way" to ignore a property from Model serialization on a collection of a type in Asp.Net Core?

For example

public sealed class MainViewModel
{
  public Guid Id { get; set; }

  [JsonIgnore("PropertyInSubViewModel")]
  public ICollection<SubViewModel> Products { get; set; }
}

The idea was to remove some property in SubViewModel from model serialization, so when I get it in my action, it would have its default value set, not the one set through the request.

Alexz S.
  • 2,366
  • 4
  • 21
  • 34
  • Why would you use a model that has properties you don't want anyway? – DavidG Sep 04 '18 at 17:12
  • Just to confirm, you want to ignore some property of `SubViewModel` when nested inside `MainViewModel`, but not when serialized independently? Or do you really want to ignore some property of `SubViewModel` when inside a specific method call? The former is quite tricky, see [Json.NET serialize by depth and attribute](https://stackoverflow.com/q/36159424). The latter might be easier, see [ASP.NET Core API JSON serializersettings per request](https://stackoverflow.com/q/44828302) plus [Exclude property from serialization via custom attribute (json.net)](https://stackoverflow.com/q/13588022). – dbc Sep 04 '18 at 18:09
  • I want to ignore a property of `SubViewModel` when nested inside `MainViewModel`, when used independently, it would expose all the properties. – Alexz S. Sep 07 '18 at 07:26

1 Answers1

2

Not with JsonIgnore. That can only be applied on the actual property that you want to ignore, and is constant at that point. However, JSON.NET does have support for conditional serialization. The easiest and most straight-forward is adding a ShouldSerialize* method to your class. You'd obviously need to determine some condition you could lean on for the determination, but that could be a straight-forward as literally setting some boolean on your sub view model instances. Basically, you just add something like:

public class SubViewModel
{
    ...

    public bool ShouldSerializePropertyInSubViewModel()
    {
         // return true or false to either allow or disallow serializing the property on this instance
    }
}
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444