rpgmaker / NetJSON

Faster than Any Binary? Benchmark: http://theburningmonk.com/2014/08/json-serializers-benchmarks-updated-2/
MIT License
231 stars 29 forks source link

After saving DateTime in UTC format, unable to retrieve it as UTC. #250

Closed DanyLinuxoid closed 4 months ago

DanyLinuxoid commented 4 months ago

If you save to file DateTime in UTC format by using '.ToUniversal()', and try to retrieve it the same way, library retrieves it in local formar without 'Kind' specified.

Just change path to file and run code:

using System;
using System.IO;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        var testme = new TestMe
        {
            DateTime = DateTime.Now.ToUniversalTime(),
        };

        await SaveContentAsync("PATH\\testNew.json", testme);
        var newFirst = await GetContentAsync<TestMe>("PATH\\testNew.json");
    }

    public async static Task SaveContentAsync<T>(string path, T content)
    {
        var result = NetJSON.NetJSON.Serialize(content);
        await File.WriteAllTextAsync(path, result);
    }

    public async static Task<T> GetContentAsync<T>(string path) where T : new()
    {
        if (!File.Exists(path))
            return new T();

        var result = NetJSON.NetJSON.Deserialize<T>(await File.ReadAllTextAsync(path));
        return result == null ? new T() : result;
    }
}

public class TestMe
{
    public DateTime DateTime { get; set; }
}

This will save DateTime as UTC. but after retrieval Date will be in local format and 'Kind' property will be 'Unspecified'

DanyLinuxoid commented 4 months ago

Fixed thanks to ChatGPT, code:

using System;
using System.Threading.Tasks;

using NetJSON;

public class Program
{
    public static async Task Main(string[] args)
    {
        // Настройки NetJSON для использования формата ISO с указанием UTC
        var settings = new NetJSONSettings
        {
            DateFormat = NetJSONDateFormat.ISO,
        };

        var testme = new TestMe
        {
            DateTime = DateTime.Now.ToUniversalTime(),
        };

        // Сериализация
        var json = NetJSON.NetJSON.Serialize(testme, settings);
        Console.WriteLine(json); // Проверка сериализованного вывода

        // Десериализация
        var recreatedObject = NetJSON.NetJSON.Deserialize<TestMe>(json, settings);
        Console.WriteLine(recreatedObject.DateTime); // Проверка десериализованного вывода
    }
}

public class TestMe
{
    public DateTime DateTime { get; set; }
}
rpgmaker commented 4 months ago

Very nice to figure the documentation with gpt