Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.net global settings

Tags:

Is there a way to specify global settings for Json.net?

The problem we're having is that it puts all DateTimes in UTC (rightly so). For legacy purposes, we want to default to Local time. I don't want to put the following code all over the place:

var settings = New JsonSerializerSettings();
settings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
JsonConvert.DeserializeObject(json, settings);
like image 779
Lodewijk Avatar asked Feb 25 '13 12:02

Lodewijk


People also ask

Is JSON NET deprecated?

Despite being deprecated by Microsoft in . NET Core 3.0, the wildly popular Newtonsoft. Json JSON serializer still rules the roost in the NuGet package manager system for . NET developers.

Does .NET support JSON?

JSON.Net is well supported and it appears that Microsoft intend to adopt it themselves "We on the web team will be including JSON.NET as the default JSON Serializer in Web API when it releases, so that'll be nice." from hanselman.com/blog/… Just be aware of the embedded library for JSon serializing's performance in .

Which is better Newtonsoft JSON or System text JSON?

Json does case-insensitive property name matching by default. The System. Text. Json default is case-sensitive, which gives better performance since it's doing an exact match.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

So, this was added to Json.net 5.0 Release 5

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Local
};

From the release notes:

Set once with JsonConvert.DefaultSettings in an application, the default settings will automatically be used by all calls to JsonConvert.SerializeObject/DeserializeObject, and JToken.ToObject/FromObject. Any user supplied settings to these calls will override the default settings.

Because there are cases where JSON should not be customized, e.g. a Facebook or Twitter library, by default JsonSerializer won’t use DefaultSettings, providing an opt-out for those frameworks or for places in your application that shouldn’t use default settings. To create a JsonSerializer that does use them there is a new JsonSerializer.CreateDefault() method.

Do note that when ASP.NET invokes Newtonsoft directly, e.g. in model binding or response formatting, it opts out of using these global default settings. To configure defaults used internally by ASP.NET see this answer by Andrei.

like image 99
Lodewijk Avatar answered Sep 28 '22 23:09

Lodewijk