C# 为什么 Json.NET DeserializeObject 将时区更改为本地时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11553760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Json.NET DeserializeObject change the timezone to local time?
提问by Dave Capper
I'm using json.net to deserialize a DateTimeOffset, but it is ignoring the specified timezone and converting the datetime to the local offset. For example, given
我正在使用 json.net 反序列化 a DateTimeOffset,但它忽略了指定的时区并将日期时间转换为本地偏移量。例如,给定
var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
When deserialised using:
反序列化时使用:
var jsonSerializerSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind };
var obj = JsonConvert.DeserializeObject(content, jsonSerializerSettings);
The obj will contain a property containing a DateTimeOffsetbut the value will be 2012-07-19T15:30:00+10:30i.e. converted to the local timezone instead of preserving the original timezone.
obj 将包含一个包含 a 的属性,DateTimeOffset但该值将被2012-07-19T15:30:00+10:30转换为本地时区而不是保留原始时区。
Is there a way to get the value to be parsed as expected so that the resulting DateTimeOffsetproperty will match the supplied value?
有没有办法让值按预期进行解析,以便结果DateTimeOffset属性与提供的值匹配?
采纳答案by Peter Ritchie
It seems to be ignoring DateParseHandling.DateTimeOffsetand is using DateParseHandling.DateTime. I would log an issue here: https://github.com/JamesNK/Newtonsoft.Json
它似乎忽略DateParseHandling.DateTimeOffset并正在使用DateParseHandling.DateTime. 我会在这里记录一个问题:https: //github.com/JamesNK/Newtonsoft.Json
回答by chopikadze
I'm not sure regarding which version did you use, because at some point of time we had the same problem, then update fixed it...
我不确定您使用的是哪个版本,因为在某些时候我们遇到了同样的问题,然后更新修复了它...
Your code works wrong for me also, but if I create class like
你的代码对我也有问题,但如果我创建类
public class A
{
public DateTimeOffset startDateTime;
}
and call
并打电话
var obj = JsonConvert.DeserializeObject<A>(content, jsonSerializerSettings);
everything works as expected. Yes, it's bug for sure, yes, I don't know how to get result exactly as YOU want, but probably, it will help for someone else.
一切都按预期工作。是的,这肯定是错误,是的,我不知道如何完全按照您的意愿获得结果,但可能对其他人有帮助。
回答by Grey Wolf
Try using this:
尝试使用这个:
microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var items = JsonConvert.DeserializeObject<List<lstObject>>(jsonString, microsoftDateFormatSettings);
I don't know if it will work in all cases but for me it did. You can try some other values for DateTimeZoneHandlingor search for more options on Google.
我不知道它是否适用于所有情况,但对我来说确实如此。您可以尝试其他一些值DateTimeZoneHandling或在 Google 上搜索更多选项。
回答by txavier
If you're using .NET WebApi you can add the following to the WebApiConfig.csfile to handle this globally in your application.
如果您使用 .NET WebApi,您可以将以下内容添加到WebApiConfig.cs文件中,以在您的应用程序中全局处理此问题。
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling =
Newtonsoft.Json.DateTimeZoneHandling.Local;
This will specifically tell the JsonFormatterto include and understand the local time zone information when serializing and deserializing a date.
这将特别告诉JsonFormatter在序列化和反序列化日期时包含和理解本地时区信息。
回答by Alexander Milchakov
This works for me, a timezone is preserved
这对我有用,保留了时区
var jss = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Local,
DateParseHandling = DateParseHandling.DateTimeOffset
};
var responseObj = JsonConvert.DeserializeObject<dynamic>(body, jss);
return responseObj.Select(s => new {
id = s["id"].Value<int>(),
date = s["date"].Value<DateTimeOffset>().DateTime,
});
A JSON body is something like this
一个 JSON 正文是这样的
[
{
"id": 211,
"date": "2017-10-22T12:00:00+03:00",
"status": 1
},
{
"id": 212,
"date": "2017-10-28T12:00:00+03:00",
"status": 1
}
]
回答by FabioLux
To use these settings in serializer, type:
要在序列化程序中使用这些设置,请键入:
var serializerSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var serializer = JsonSerializer.Create(serializerSettings);
回答by Adel Nasiri
As a simple way, you can Convert Dateto Ticksfor serializing and convert it from Ticksto Datefor deserializing:
作为一个简单的方法,你可以转换Date到Ticks序列化,并将其从转换Ticks到Date对反序列化:
Serializing:
序列化:
DateTime date = new DateTime();
ticks = date.Ticks
Deserializing"
反序列化”
Datetime = new Datetime(ticks);
回答by Val
To use the correct Local Datewith custom JsonConverter, do:
要使用正确Local Date的 custom JsonConverter,请执行以下操作:
var obj = JsonConvert.DeserializeObject(json, type, new JsonSerializerSettings {
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Local,
Converters = new JsonConverter[] { new MY_CUSTOM_CONVERTER() }
});
I search hard on the internet to combine them together, and eventually found JsonConvertercan be feed into JsonSerializerSettings.
我在互联网上努力搜索将它们组合在一起,最终发现JsonConverter可以输入JsonSerializerSettings.

