59

I am new to ASP.Net Web Api Core. I have been using ASP.Net MVC for past few years and I always have written an ActionFilter and used JSON.Net for Serializing data into JSON. So, in that way I replaced Microsoft's JavaScript Serializer (which is slower than JSON.Net) with JSON.Net (it is claimed to be 400% faster).

How to do all this in ASP.Net Web Api Core? Where to change the default formattor?

Note: Please feel free to ask if you have any questions.

Thanks

Zeshan Munir
  • 1,058
  • 1
  • 14
  • 23

3 Answers3

72

In .NET Core 3.0+ include the NuGet package Microsoft.AspNetCore.Mvc.NewtonsoftJson and then replace

services.AddControllers();

in ConfigureServices with

services.AddControllers().AddNewtonsoftJson();

This is a pre-release NuGet package in .NET Core 3.0 but a full release package in .NET Core 3.1.

I came across this myself, but I've found that the same answer with some additional info is in this SO question and answer.

Edit: As a useful update: code with the call to AddNewtonsoftJson() will compile and run even without installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package. If you do that, it runs with both converters installed, but defaulting to the System.Text.Json converter which you presumably don't want since you're reading this answer. So you must remember to install the NuGet package for this to work properly (and remember to re-install it if you ever clear down and redo your NuGet dependencies).

MikeBeaton
  • 3,314
  • 4
  • 36
  • 45
  • this saved my lot of time, and i was able to migrate to .net 3.1. seamlessly – Imran Rizvi Apr 08 '22 at 10:17
  • This saves me! Thanks. I upgraded my application from 2.2 to 6. There are lots of cases that uses dynamics object. So instead of resolving them on every case, I tried this solution and it works like a charm. Thank you. services.AddControllers().AddNewtonsoftJson(); – CherryBlossom Oct 27 '22 at 00:38
  • I did same, but this is breaking my JsonConvert.DeserializeObject. Below is what I did after getting response from controller: var res = response.Content.ReadAsStringAsync().Result; var validationResponse = JsonConvert.DeserializeObject(res); Its breaking at the desterilize line. If I use services.AddControllers(); only, post will work, but patch wont. – Mayur Saner Jun 23 '23 at 13:35
34

ASP.NET Core already uses JSON.NET as JavaScriptSerializer isn't implemented/ported to .NET Core.

Microsoft.AspNetCore.Mvc depends on Microsoft.AspNetCore.Formatter.Json which depends on Microsoft.AspNetCore.JsonPatch, which depends on Newtonsoft.Json (see source).

Update

This is only true for ASP.NET Core 1.0 to 2.2. ASP.NET Core 3.0 removes the dependency on JSON.NET and uses it's own JSON serializer.

Community
  • 1
  • 1
Tseng
  • 61,549
  • 15
  • 193
  • 205
  • Hi Tseng. Thanks for taking time and helping. I have commented out the newtonsoft's dependency in project.json but web api is still working, how is that? – Zeshan Munir Feb 17 '17 at 07:33
  • 1
    It told you already. You are referencing one (likely `Microsoft.AspNetCore.Mvc´) and it references Formatter.Json and it has dependency on JsonPatch and JsonPatch finally brings in Newtonsoft.Json. You can't "comment out" the JSON.NET dependency unless you remove all Mvc related packages, but then you got a console application – Tseng Feb 17 '17 at 08:00
  • So basically, even if I remove the reference, it still loads it because JSON.Net is a dependency for JsonPatch? Got it. Thanks. – Zeshan Munir Feb 22 '17 at 09:11
  • 3
    @SuperCoder: Exactly. It will however load the version which is referenced by MVC (9.0.1 as of ASP.NET Core MVC 1.1). If you want a newer version (i.e. Json.NET 9.0.2-beta2 for example), then you need to add the reference yourself to your application csproj/project.json – Tseng Feb 22 '17 at 11:29
  • Great info... I discovered the version used by the .Net Core MVC is `Newtonsoft.Json v9.0.1` – Jaider Oct 14 '17 at 23:59
  • Great answer. I just Write JsonConvert and resolve the namespace and it's automatically showing the Newtonsoft.Json – Hassaan Aug 11 '18 at 18:59
  • Author of Newtonsoft.Json JamesNK works at Microsoft dotnet team since end of March 2018. https://twitter.com/jamesnk/status/978719138347495424. Guess what stands behind the Json serializer in .NET Core 3.0? I liked this. – Demir Jun 21 '19 at 19:50
  • @Demir: One of the reasons for `System.Text.Json` is to remove the dependency of ASP.NET Core on JSON.NET (since it was quite hard to use a newer version of JSON.NET with ASP.NET Core since its build on a specific version, i.e. as time of writing of the answer 9.0.1). The other is performance and that the author doesn't want breaking changes (new Span Api would require that) and its would be a major rewrite of the hole library – Tseng Jun 22 '19 at 13:35
6

here is a code snippet to adjust the settings for a .net core application

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddJsonOptions(options => {
            // send back a ISO date
            var settings = options.SerializerSettings;
            settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
            // dont mess with case of properties
            var resolver = options.SerializerSettings.ContractResolver as DefaultContractResolver;
            resolver.NamingStrategy = null;
        });
}
Kieran
  • 17,572
  • 7
  • 45
  • 53
  • 3
    This code is for setting the default configurations of the Newtonsoft.json not for changing the serializer. – Zeshan Munir Feb 08 '19 at 20:51
  • so this works, but i need special cases, i.e. sometime i might just need yyyy-MM-dd. I've got a custom attribute for this, `[JsonConverter(typeof(DateOnlyConverter))]` that works with regular newtonsoft, how do i make `Microsoft.AspNetCore.Mvc.NewtonsoftJson` recognize my custom attribute? – MikeT Mar 18 '21 at 23:20