LoginSignup
3
2

More than 1 year has passed since last update.

[.NET][C#] 日付のJSONデシリアライズ

Last updated at Posted at 2019-08-26

前書き

.NET Framework界隈では、Newtonsoft.Jsonがデファクトスタンダードでしょうか。

Newtonsoft.Jsonを使ってSystem.DateTime型を変換するときには、タイムゾーンの扱いに応じて4つのオプション Local Utc Unspecified RoundtripKind があります。

ドキュメントを読んでもいまいちわからなかったので実際に動かしてみました。

実験結果

デシリアライズ

2019-12-31T15:00:00.000Z という日付をデシリアライズすると、、、

オプション DateTimeの値 DateTime.Kindの値
Local 2020-01-01 00:00:00 Local
Utc 2019-12-31 15:00:00 Utc
Unspecified 2019-12-31 15:00:00 Unspecified
RoundtripKind 2019-12-31 15:00:00 Utc

シリアライズ

シリアライズは、ドキュメントにある通りです。まとめてみます。

DateTime.Kindの値
オプション Unspecified Utc Local
Local 2013-01-21T00:00:00+09:00 2013-01-21T00:00:00+09:00 2013-01-21T00:00:00+09:00
Utc 2013-01-21T00:00:00Z 2013-01-21T00:00:00Z 2013-01-20T15:00:00Z
Unspecified 2013-01-21T00:00:00 2013-01-21T00:00:00 2013-01-21T00:00:00
RoundtripKind 2013-01-21T00:00:00 2013-01-21T00:00:00Z 2013-01-21T00:00:00+09:00

実験ソース

ソースコードはこちらに置きました。
https://github.com/sengokyu/ex-DateTimeZoneHandling

dotnet runコマンドで実行できます。

考察

自分の要件ではUTCがよさげです。

JSON UTC文字列 -> UTCなSystem.DateTime
Kind=LocalなSystem.DateTime -> JSON UTC文字列

System.DateTimenewするときは、Kindを忘れずにLocalにセットしないとです。

ASP.Net Coreにおける設定

starup.csの中で、.AddJsonFormatters()を呼び出すときにオプションを渡します。

services.AddJsonFormatters(options =>
{
    options.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
})
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2