(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
応用すれば色々書ける。