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

json.net: DateTimeStringConverter gets an already DateTime converted object in ReadJson()(json.net:DateTimeStringConverter 在 ReadJson() 中获取已经 DateTime 转换的对象)
本文介绍了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 转换的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)