Newtonsoft.Json自定义日期序列化 [英] Newtonsoft.Json customize date serialization

查看:81
本文介绍了Newtonsoft.Json自定义日期序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Newtonsoft.Json 将日期从C#序列化为JSON.我想做的是让json序列化程序使用当前的区域性将日期格式化为字符串.

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

这是我的Json序列化程序提供的信息:

Here is what I am getting by my Json serializer:

JsonConvert.SerializeObject(DateTime.Now);

结果是:

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

但是我更喜欢的是:

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

因为我当前的文化是巴西,我希望以上述方式显示日期.

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

是否有可能全局(对于可能被序列化的任何日期)告诉Newtonsoft.Json中的json序列化器,就好像在执行 date.ToString()(因为ToString尊重 System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat 中的区域性,并相应地提供了正确的格式)

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)

推荐答案

您需要设置 JsonSerializerSettings.DateFormatString 设置为您想要的格式.

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.

这篇关于Newtonsoft.Json自定义日期序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆