Reputation: 121
I added NewtonsoftJson as middleware in .net core 3.1. I would love to move over to new System.Text.Json serializer.
I can´t just jump over but is there way to use the one from System.Text.Json in one method some how. More or less it is one that I need to speed up.
Added: I have in startup
services.AddControllers(options => options.RespectBrowserAcceptHeader = true)
.AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
My migration proplem is that I can not just change this to System.Text.Json all at once. So if I could change one controller or just one method in controller to use System.Text.Json version that would solve my problem.
Upvotes: 12
Views: 7873
Reputation: 438
Starting with .Net 6, System.Text.Json supports ignoring circular references and can be used like this
services.AddControllers()
.AddJsonOptions(options => {options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;});
See here for more info: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-preserve-references?pivots=dotnet-6-0
Upvotes: 36
Reputation: 116785
This is not currently implemented in .Net 3.1. The current migration guide How to migrate from Newtonsoft.Json to System.Text.Json: Scenarios that JsonSerializer currently doesn't support : Preserve object references and handle loops states:
Newtonsoft.Json
also has aReferenceLoopHandling
setting that lets you ignore circular references rather than throw an exception.System.Text.Json only supports serialization by value and throws an exception for circular references.
See also the github issue System.Text.Json Reference Loop Handling #29900 where this is stated to be a "known limitation" - but there is a current milestone for release which is .Net Core 5.0. The proposed specification is here: https://github.com/dotnet/runtime/blob/master/src/libraries/System.Text.Json/docs/ReferenceHandling_spec.md
Upvotes: 2