0

We upgraded a .NET core 2.2 project to .NET 6 and were having some issues with Newtonsoft.Json so decided to switch to using System.Text.Json;

Was able to find most of the conversions online:

switching to System.Text.Json nodes Equivalent of JObject in System.Text.Json

and from:

var value = JsonSerializer.Serialize(allImages);

to

var value = JsonConvert.SerializeObject(allImages);

etc... https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-8-0

My question is I can't find the conversion for the program.cs file

JsonConvert.DefaultSettings = () =>
{
    return new JsonSerializerSettings()
    {
        NullValueHandling = NullValueHandling.Ignore,
        MissingMemberHandling = MissingMemberHandling.Ignore,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
};

How can I convert the above code from Newtonsoft.Json to System.Text.Json please?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
John
  • 3,965
  • 21
  • 77
  • 163
  • 2
    [How to instantiate JsonSerializerOptions instances with System.Text.Json](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/configure-options) and what's on the left in that *node* -- You have inverted parts in your from / to section -- You should probably migrate to .NET 7 instead of .NET 6 (also because of System.Text.Json) – Jimi Jun 07 '23 at 21:47
  • "were having some issues with Newtonsoft.Json" . Now you are going to have a lot more issues with Text.Json. Stop it , the sooner the better – Serge Jun 08 '23 at 00:03
  • 1
    Or consider changing to .NET 7. It's important to realize that .NET 6 is the _Long Term Support_ release. Staying on 6 buys you an extra six months of Support. Plan on moving to 8 when it's released – Flydog57 Jun 08 '23 at 01:40
  • There is no equivalent to Json.NET's [`JsonConvert.DefaultSettings`](https://www.newtonsoft.com/json/help/html/DefaultSettings.htm). See [How to globally set default options for System.Text.Json.JsonSerializer?](https://stackoverflow.com/q/58331479) which tracks an upen github issue and several workarounds. – dbc Jun 08 '23 at 13:36
  • Close as a duplicate of [How to globally set default options for System.Text.Json.JsonSerializer](https://stackoverflow.com/q/58331479)? – dbc Jun 08 '23 at 23:02

1 Answers1

0

Here you go. Please read the comments from the code.

.AddJsonOptions(option => {
    option.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    option.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

    //You need the DevBetter.JsonExtensions from nuget to have this extension method
    option.JsonSerializerOptions.SetMissingMemberHandling(MissingMemberHandling.Ignore);
});
Maico
  • 171
  • 5