DateTimeStringConverter在ReadJson

DateTimeStringConverter在ReadJson

本文介绍了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.

是错误还是功能?

推荐答案

这是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.

如果您使用自己的日期转换器,或者想要自己处理日期解析,则需要确保设置 DateParseHandling JsonSerializerSettings中设置为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转换的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:13