Newtonsoft.Json adjusts serialization dates

I am using Newtonsoft.Json to serialize my dates from C # to javscript, what I want to do is use the json serializer for the current date to format the dates in a string

Here is what I get from my Json serializer:

 JsonConvert.SerializeObject(DateTime.Now); 

result:

 "2016-07-08T17:10:17.6722753-05:00" 

But I prefer:

 "08/07/2016 17:10:57" 

Because my current culture is Brazilian and I want my dates to be displayed higher.

Is it possible globally (for any date that can be serialized) tell json serializer in Newtonsoft.Json to use it as if it were date.ToString() (since ToString respects the culture in System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat and gives the appropriate format)

+7
json c # serialization
source share
2 answers

You need to install JsonSerializerSettings.DateFormatString in the desired format.

 var jsonSettings = new JsonSerializerSettings(); jsonSettings.DateFormatString = "dd/MM/yyy hh:mm:ss"; string json = JsonConvert.SerializeObject(someObject, jsonSettings); 

After that, you can either pass the settings object every time you use the serializer, or follow the steps in the answer that dbc refers to. Although you do not specify where it works (ASP.NET, desktop, UWP, etc.), therefore, how you can install it globally may differ.

+18
source share

Yes, you can use the converter in the JsonSerializer settings.

 public class SpecialDateTimeConverter : DateTimeConverterBase { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { writer.WriteValue(((DateTime)value).ToString("dd/MM/yyyy hh:mm:ss")); } } string convertedDateTime = JsonConvert.SerializeObject(DateTime.Now, Formatting.Indented, new SpecialDateTimeConverter()); 
0
source share

All Articles