LoginSignup
4
1

More than 1 year has passed since last update.

json内の日付フォーマットがそのままではSystem.Text.Jsonで解釈されないときのConverter

Posted at

(Newtonsoft じゃなく、text.jsonの方)

JSON中の日付フォーマットがそのままではパースできないことがある(多々)

例えば

{
"created_at": "2019/06/08 05:47:17"
}

こういう日付形式だとDateTimeにパースされない。

Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $.data[0].attributes.created_at | LineNumber: 74 | BytePositionInLine: 43.
 ---> System.FormatException: The JSON value is not in a supported DateTime format.
   at System.Text.Json.Utf8JsonReader.GetDateTime()
…

こんなException吐きます。

Converter書く

ビルトインなクラスにあればいいんだが、自分でConverterの実装書かないといけないみたい。

参照)
https://docs.microsoft.com/ja-jp/dotnet/standard/datetime/system-text-json-support#custom-support-for--and-
(ドキュメントって得てして読みにくいもんだよね…

converter.cs
    public class DateTimeJsonConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
        {
            if (reader.GetString()! == null) return DateTime.MinValue;
            return DateTime.ParseExact(reader.GetString()!,
                "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
        }

        public override void Write(
            Utf8JsonWriter writer,
            DateTime dateTimeValue,
            JsonSerializerOptions options) =>
            writer.WriteStringValue(dateTimeValue.ToString(
                "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture));
    }

マッピングするクラス側

class.cs
public class Hoge
{
  [JsonConverter(typeof(DateTimeJsonConverter))]
  public DateTime created_at { get; set; }
}

シリアライズのコード

main.cs
var obj = JsonSerializer.Deserialize<Hoge>(json);

でOK

応用すれば色々書ける。

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