Newtonsoft.Json customize serialize dates

被刻印的时光 ゝ 提交于 2019-12-09 14:43:58

问题


I am using Newtonsoft.Json for serializing my dates from C# to javscript what I want to do is have the json serializer use the current culture for formatting dates into string

Here is what I am getting by my Json serializer:

JsonConvert.SerializeObject(DateTime.Now);

result is:

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

But what I prefer is:

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

Because my current culture is brazil and I want my dates to be displayed the above way.

Is it possible to Globally( for any date that may be serialized) tell the json serializer in Newtonsoft.Json to use as if it is doing the date.ToString()(because ToString respects the culture in System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat and gives the right format accordingly)


回答1:


You'll want to set JsonSerializerSettings.DateFormatString to your 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 in each time you use the serializer, or follow the steps in the answer referenced by dbc. Although, you don't mention where this is running (ASP.NET, desktop, UWP, etc), so how you set it globally may differ.




回答2:


Yes you can use a 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());


来源:https://stackoverflow.com/questions/38276174/newtonsoft-json-customize-serialize-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!