0

In my controller I am returning an object of a class with ShouldSerialize{PropertyName}() methods in it but it looks like these methods are not called when MVC action methods are invoked. I even tried returning 'false' as you see commented out in the code below with no luck.

public Department Department { get; set; }

public bool ShouldSerializeDepartment()
{
    return Department != null;
    // return false;
}

That means, Asp.Net MVC does not call JsonConvert.SerializeObject behind the scenes otherwise conditional serialization would be effective (Am I right?).

Does anyone know how to get it to work?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rez.Net
  • 1,354
  • 2
  • 19
  • 28
  • 1
    Correct, ASP.NET MVC 5 does not use Json.Net; it uses `JavaScriptSerializer`. Therefore it will not honor Json.Net attributes or `ShouldSerialize` methods. See [Newtonsoft JSON for .net is ignoring jsonproperty tags](https://stackoverflow.com/q/24897579/10263). See also [Setting the default JSON serializer in ASP.NET MVC](https://stackoverflow.com/q/14591750/10263). – Brian Rogers Feb 19 '20 at 06:15
  • 1
    thanks @BrianRogers, that sheds lights on this dilemma of mine :) if you put it as an answer I will mark it as the right one. – Rez.Net Feb 20 '20 at 00:16

0 Answers0