部分反序列化Web API核心控制器 [英] Partial deserialization Web API Core controller

查看:66
本文介绍了部分反序列化Web API核心控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的对象

I have an object defined as such

public class FilingSearchCriteria
{
    public int? FilerId { get; set; }
    public int? TypeId { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public bool? Legacy { get; set; }
    public bool? NoAtttachments { get; set; }
    public bool? MissingFields { get; set; }
    public bool? MissingAttachments { get; set; }
    public string DocketNumber { get; set; }
 
}

Net Core控制器将其作为参数.问题通常是出现的JSON通常仅具有其中一些属性(通过设计),这似乎会导致反序列化失败,因此我的控制器获得的是上述对象,所有属性均设置为null.

A a Net Core controller takes it as a parameter. Issue is most of the time the JSON that comes only has a few of those properties (by design), which seems to cause a deserialization failure so what my controller gets is the above object with all properties set to null.

我如何告诉默认的网络核心 system.text.json serialzier接受部分"请求?这样的对象?

How can I tell the default net core system.text.json serialzier to accept "partial" object like that?

添加传入的JSON

{"EndDate":"Tue, 02 Feb 2021 18:07:33 GMT","StartDate":"Tue, 26 Jan 2021 18:07:33 GMT"}

推荐答案

您的 StartDate EndDate 属性不在.来自 System.Text中的DateTime和DateTimeOffset支持.杰森:

Your StartDate and EndDate properties are not in ISO 8601-1:2019 format, which would look like "2021-02-02T18:07:33Z" instead of "Tue, 02 Feb 2021 18:07:33 GMT". From DateTime and DateTimeOffset support in System.Text.Json:

JsonSerializer,Utf8JsonReader,Utf8JsonWriter和JsonElement类型根据ISO 8601-1:2019格式的扩展配置文件解析并写入DateTime和DateTimeOffset文本表示形式;例如,2019-07-26T16:59:57-05:00.
...
使用默认选项时,输入的DateTime和DateTimeOffset文本表示必须符合扩展的ISO 8601-1:2019配置文件.尝试反序列化不符合概要文件的表示形式将导致JsonSerializer抛出JsonException.

The JsonSerializer, Utf8JsonReader, Utf8JsonWriter, and JsonElement types parse and write DateTime and DateTimeOffset text representations according to the extended profile of the ISO 8601-1:2019 format; for example, 2019-07-26T16:59:57-05:00.
...
With default options, input DateTime and DateTimeOffset text representations must conform to the extended ISO 8601-1:2019 profile. Attempting to deserialize representations that don't conform to the profile will cause JsonSerializer to throw a JsonException.

因此,您将需要按照Microsoft在DateTimeConverterUsingDateTimeParse 的行创建自定义 JsonConverter< DateTime?> .microsoft.com/zh-cn/dotnet/standard/datetime/system-text-json-support#custom-support-for--and-"rel =" nofollow noreferrer>对DateTime和DateTimeOffset的自定义支持例如:

Thus you will need to create a custom JsonConverter<DateTime?> along the lines of DateTimeConverterUsingDateTimeParse that Microsoft shows in Custom support for DateTime and DateTimeOffset such as:

public class CustomDateTimeConverter : JsonConverter<DateTime?>
{
    //const string Format = "Tue, 02 Feb 2021 18:07:33 GMT";
    const string Format = "dddd, dd MMM yyyy hh:mm:ss";

    // Adapted from https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support#using-datetimeoffsetparse-and-datetimeoffsettostring
    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
        DateTime.Parse(reader.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) =>
        writer.WriteStringValue(value?.ToUniversalTime().ToString(Format, CultureInfo.InvariantCulture)+" GMT");
}

然后可以将转换器添加到 JsonSerializerOptions.Converters 或将其直接应用于模型,如下所示:

You can then add the converter to JsonSerializerOptions.Converters or apply it directly to the model like so:

public class FilingSearchCriteria
{
    public int? FilerId { get; set; }
    public int? TypeId { get; set; }

    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime? StartDate { get; set; }
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime? EndDate { get; set; }
    // Remainder unchanged

注意:

  • System.Text.Json似乎需要不同的

  • System.Text.Json seems to require distinct JsonConverter<T> converters for DateTime? and DateTime -- and generally for nullables and their underlying types.

DateTime.Parse()显然不支持解析多个名称时区,因此,如果您接收到带有不同时区混合的 DateTime 字符串,请说"GMT" "EDT" 将需要编写一个更复杂的转换器.

DateTime.Parse() apparently does not support parsing multiple names time zones so if you are receiving DateTime strings with a mixture of different time zones, say both "GMT" and "EDT", you will need to write a more complex converter.

我的转换器假定您希望将日期和时间调整为通用.您可以根据需要进行修改.

My converter assumes you want your dates and times adjusted to universal. You can modify that if it is not desired.

演示小提琴此处.

这篇关于部分反序列化Web API核心控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆