LoginSignup
4
4

More than 5 years have passed since last update.

Json.NET でシリアライズ/デシリアライズ時に日付フォーマットを指定する

Posted at

Json.NETがとても便利なのです。
Json.NET logo

基本的にはこちらのC#でJSONを扱うライブラリ「Json.NET」を使ってみましたでまとめられています。

DateTime型のフィールドを扱いたい

モデル上ではDateTime型で扱い、JSONにパースする際は決まったフォーマットで扱いたい。
あるいは、決まったフォーマットの日付文字列をDateTime型のフィールドに収めたい。
皆さんこんな気持ちありますよね。

そんな時にはDateTimeConverterを SerializeObject()DeserializeObject() に渡してあげます。
http://www.newtonsoft.com/json/help/html/datesinjson.htm

僕はISO8601のフォーマット(+09:00付き)としたかったのでこんな感じになりました。

using NewtonSoft.Json;
using NewtonSoft.Json.Converters;

// Serialize
var jsonStr = JsonConvert.SerializeObject(json, new IsoDateTimeConverter());

// Deserialize
var json = JsonConvert.DeserializeObject<Model>(jsonStr, new IsoDateTimeConverter());

何と簡単!

すでに引数へJsonSerializerSettingsを渡している場合

using NewtonSoft.Json;
using NewtonSoft.Json.Converters;

// Serialize
var jsonStr = JsonConvert.SerializeObject(json, new JsonSerializerSettings { Converters = { new IsoDateTimeConverter() } });

// Deserialize
var json = JsonConvert.DeserializeObject<Model>(jsonStr, new JsonSerializerSettings { Converters = { new IsoDateTimeConverter() } });

こちらも簡単ですね。

カスタムフォーマットの場合

new IsoDateTimeConverter { DateTimeFormat = "yyyy年MM月dd日 HH時mm分ss秒" };

とやると、できるとかできないとか。(未検証)

4
4
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
4
4