Serialize NodaTime JSON

前端 未结 2 1823
南方客
南方客 2021-02-10 07:40

I am making a prototype project of NodaTime compared to BCL\'s DateTime, but executing this result gives me recursionLimit exceeded error.

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-10 07:53

    Serialization is supported for JSON.NET in Noda Time 2.0+.

    You'll need to install the package with NuGet:

    > Install-Package NodaTime.Serialization.JsonNet
    

    And then configure your serializer settings to use it. This won't work with the default serializer/deserializer - you need to configure one explicitly.

    We chose to use one statically. Your usage may be different. Here is an example:

    using Newtonsoft.Json;
    using NodaTime;
    using NodaTime.Serialization.JsonNet; // << Needed for the extension method to appear!
    using System;
    
    namespace MyProject
    {
        public class MyClass
        {
            private static readonly JsonSerializerSettings _JsonSettings;
    
            static MyClass()
            {
                _JsonSettings = new JsonSerializerSettings
                {
                    // To be honest, I am not sure these are needed for NodaTime,
                    // but they are useful for `DateTime` objects in other cases.
                    // Be careful copy/pasting these.
                    DateFormatHandling = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                };
    
                // Enable NodaTime serialization
                // See: https://nodatime.org/2.2.x/userguide/serialization
                _JsonSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            }
    
            // The rest of your code...
        }
    }
    

提交回复
热议问题