【发布时间】:2021-09-10 18:21:35
【问题描述】:
使用 NewtonSoft,我们可以使用reader.Path 获取路径。 System.Text.Json 没有这个。
namespace API.JsonConverters
{
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
/// <summary>
/// Use DateTime.Parse to replicate how Newtonsoft worked.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support</remarks>
public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
try
{
return DateTime.Parse(reader.GetString(), styles: System.Globalization.DateTimeStyles.RoundtripKind);
}
catch (FormatException)
{
// We have to do this to have the Path variable auto populated so when the middleware catches the error, it will properly populate the ModelState errors.
// https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#error-handling
// https://github.com/dotnet/aspnetcore/blob/release/3.1/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs#L79
throw new JsonException("Invalid DateTime. Please use RoundTripKind (MM-DD-YYYY) - https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-round-trip-date-and-time-values");
}
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("o"));
}
}
}
如何访问当前路径,以便我可以从自定义 JsonConverter 的 Read() 方法中抛出同时包含自定义消息和 Path 的异常?
【问题讨论】:
-
Utf8JsonReader似乎根本没有跟踪路径。它只跟踪BitStack和Utf8JsonReader._bitStack中的容器类型(对象或数组)堆栈。 -
JsonSerializer确实使用ReadStack.JsonPath()跟踪此信息。不幸的是,ReadStack是内部的,不公开。
标签: c# asp.net-mvc asp.net-core system.text.json