json.net:DateTimeStringConverter 在 ReadJson() 中获取已经 DateTime

时间:2023-04-25
本文介绍了json.net:DateTimeStringConverter 在 ReadJson() 中获取已经 DateTime 转换的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

先决条件:

  • JSON.Net 11.0.2

我需要通过基于 JSON 的 REST-API 存储 UTC DateTime 往返日期/时间模式.

I need to store the UTC DateTime round-trip date/time pattern via a JSON based REST-API.

string utcTimestamp = DateTime.UtcNow.ToString( "o" );
// 2018-11-27T22:35:32.1234567Z

所以我给自己写了一个 DateTimeStringConverter 以确保不涉及本地文化信息.

So I wrote myself a DateTimeStringConverter to ensure no local culture information gets involved.

class DateTimeStringConverter:
    JsonConverter<DateTime>
{
    public override void WriteJson( JsonWriter writer, DateTime value, JsonSerializer serializer )
    {
        string convertedValue = value.ToString( "o" );
        writer.WriteValue( convertedValue );
    }

    public override DateTime ReadJson( JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer )
    {
        string value = reader.Value.ToString( );
        DateTime convertedValue = DateTime.Parse( value ).ToLocalTime( );
        return convertedValue;
    }
}

我很困惑为什么我得到一个没有毫秒的 DateTime 对象.经过大量的尝试和错误,我进入了它.

I was very confused as to why I was getting a DateTime object without the milliseconds. After a lot of trial and error, I got into it.

public override DateTime ReadJson( JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer )
{
    Console.WriteLine( reader.Value.GetType( ).ToString( ) );
    // System.DateTime

    string value = reader.Value.ToString( );
    DateTime convertedValue = DateTime.Parse( value ).ToLocalTime( );
    return convertedValue;
}

JSON.Net 为我提供了一个已转换的 DateTime 对象,以便我自己反序列化,而无需任何毫秒数据.我没有找到任何关于它是错误还是功能的线索.

JSON.Net serves me an already converted DateTime object to deserialize on my own without any millisecond data. I didn't find any clues as to whether it is a bug or a feature.

为了反查,我写了一个 BooleanStringConverter.

To counter check it I wrote a BooleanStringConverter.

class BoolStringConverter:
    JsonConverter<bool>
{
    public override void WriteJson( JsonWriter writer, bool value, JsonSerializer serializer )
    {
        string convertedValue = false == value ? "False" : "True";
        writer.WriteValue( convertedValue );
    }

    public override bool ReadJson( JsonReader reader, Type objectType, bool existingValue, bool hasExistingValue, JsonSerializer serializer )
    {
        Console.WriteLine( reader.Value.GetType( ).ToString( ) );
        // System.String

        string value = ( string ) reader.Value;
        bool convertedValue = "False" == value ? false : true;
        return convertedValue;
    }
}

JSON.Net 不为我提供已转换的 bool 对象.

JSON.Net doesn't serve me an already converted bool object.

这是一个错误还是一个功能?

Is it a bug or is it a feature?

推荐答案

这是 Json.Net 的已知行为.由于 JSON 没有用于表示日期的内置语法(就像它用于布尔值一样),它们必须表示为字符串.默认情况下,Json.Net 会尽力为您解析看起来像日期的字符串.

This is a known behavior of Json.Net. Since JSON does not have a built-in syntax for denoting dates (like it does for booleans), they have to be represented as strings. By default Json.Net tries to be nice and parse date-looking strings for you.

如果您使用自己的日期转换器,或者想自己处理日期解析,则需要确保设置 DateParseHandlingJsonSerializerSettings 中设置为 None,否则内部阅读器将尝试先处理它.

If you are using your own converter for dates, or otherwise want to handle date parsing yourself, you need to be sure to set the DateParseHandling setting to None in the JsonSerializerSettings, otherwise the internal reader will try to handle it first.

JsonSerializerSettings settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new DateTimeStringConverter() },
    DateParseHandling = DateParseHandling.None
};

var foo = JsonConvert.DeserializeObject<Foo>(json, settings);

这篇关于json.net:DateTimeStringConverter 在 ReadJson() 中获取已经 DateTime 转换的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 JSON.NET 解析格式 Date(epochTime-offset) 的 json 日期 下一篇:使用非默认构造函数会破坏 Json.net 中的反序列化顺序

相关文章