ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,jQuery Plugins,jQuery UI,SSRS,XML,HTML,jQuery demos,code snippet examples.

Breaking News

  1. Home
  2. .NET CORE
  3. ASP.NET
  4. C #
  5. Using Newtonsoft.Json In .NET Core 3+ Projects

Using Newtonsoft.Json In .NET Core 3+ Projects

Recently I’ve been working a lot in .NET Core 3.0 and 3.1 projects. Both upgrading existing 2.2 projects and a couple of new greenfields projects. The thing that I’ve had to do in each and every one is switch from using the new System.Text.Json package back to using Newtonsoft.Json.

In almost all of them I’ve actually tried to keep going with System.Text.Json, but in the existing projects I haven’t had time to switch out things like custom JsonConverters or Newtonsoft.Json specific attributes on my models.

In new projects, I always get to the point where I just know how to do it in Newtonsoft. And as much as I want to try this shiny new thing, I have my own deadlines which don’t quite allow me to fiddle about with new toys.

So if you’re in the same boat as me and just need to get something out the door. The first thing you need is to install the following Nuget package :

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

Then you need to add a specific call to your IMVCBuilder. This will differ depending on how you have set up your project. If you are migrating from an existing project you’ll have a call to “AddMvc()” which you can then tack onto it like so :

services.AddMvc().AddNewtonsoftJson();

However in new .NET Core 3+ projects, you have a different set of calls replace MVC. So you’ll probably have one of the following :

services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();

If this is an API you will likely have AddControllers, but depending on your project setup you could have the others also. Tacking on AddNewtonsoftJson()  to the end means it will “revert” back to using Newtonsoft over System.Text.Json

No comments