neuecc / Utf8Json

Definitely Fastest and Zero Allocation JSON Serializer for C#(NET, .NET Core, Unity, Xamarin).
MIT License
2.36k stars 267 forks source link

What is the preferred way to deserialize unix timestamp? #71

Open Gorthog opened 6 years ago

Gorthog commented 6 years ago

For example I want to deserialize '{"date":1512465020}' into class:

    public class File
    {
        [DataMember(Name = "date")]
        public DateTime UpdateDate { get; set; }
    }
Gorthog commented 6 years ago

I tried adding the following attribute (and removing DataMember):

        [JsonFormatter(typeof(UnixTimestampDateTimeFormatter))]
        public DateTime date { get; set; } 

With or without it I get the error "Utf8Json.JsonParsingException: 'expected:'String Begin Token', actual:'1512465020', at offset:8'"

Also tried:

            CompositeResolver.RegisterAndSetAsDefault(
                new IJsonFormatter[] {
                 new UnixTimestampDateTimeFormatter(),
                }
                , new[] {
                    StandardResolver.Default
                });

Same error.

Full stack trace:

Utf8Json.JsonParsingException: expected:'String Begin Token', actual:'1512465020', at offset:8 at void Utf8Json.JsonReader.ReadStringSegmentCore(out byte[] resultBytes, out int resultOffset, out int resultLength) at ArraySegment Utf8Json.JsonReader.ReadStringSegmentUnsafe() at DateTime Utf8Json.Formatters.UnixTimestampDateTimeFormatter.Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) at NameFromFile Utf8Json.Formatters.DataUploader_Dto_NameFromFileFormatter1.Deserialize(ref JsonReader, IJsonFormatterResolver) at T Utf8Json.JsonSerializer.Deserialize(byte[] bytes, int offset, IJsonFormatterResolver resolver) at T DataUploader.Json.Utf8JsonSerializer.Deserialize(string json) in C:/DataUploader/Json/Utf8JsonSerializer.cs:line 15 at IEnumerable DataUploader.FileImporters.NameFileImporter.ReadVertex()+MoveNext() in C:/DataUploader/FileImporters/NameFileImporter.cs:line 30 at TSource System.Linq.Enumerable.TryGetFirst(IEnumerable source, out bool found) at TSource System.Linq.Enumerable.FirstOrDefault(IEnumerable source) at void DataUploader.Program.Main(string[] args) in C:/DataUploader/Program.cs:line 15

neuecc commented 6 years ago

Could you provide full code? I can't reproduce it.

public class File
{
    [JsonFormatter(typeof(UnixTimestampDateTimeFormatter))]
    public DateTime UpdateDate { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // ok to serialize
        var jsbin = JsonSerializer.Serialize(new File { UpdateDate = DateTime.Now  });
        Console.WriteLine(JsonSerializer.PrettyPrint(jsbin)); // { "UpdateDate": "1524480923" }

        // ok to deserialize
        var foo = JsonSerializer.Deserialize<File>(jsbin);
        Console.WriteLine(foo.UpdateDate);
    }
}
Gorthog commented 6 years ago

Hi, thanks for the response. here is the code that fails for me, note no quotes around unix time:

        public class File
        {
            [JsonFormatter(typeof(UnixTimestampDateTimeFormatter))]
            public DateTime UpdateDate { get; set; }
        }

        static void Main(string[] args)
        {
            try
            {
                var str = @"{ ""UpdateDate"":1512465020}";
                // ok to deserialize
                var foo = JsonSerializer.Deserialize<File>(str);
                Console.WriteLine(foo.UpdateDate);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Demystify());
            }
        }
neuecc commented 6 years ago

Yes, Currently UnixTimestampDateTimeFormatter only allows string data. https://github.com/neuecc/Utf8Json/blob/d41ec0060bc1c86a5ecf2557dc0a42def5d27853/src/Utf8Json/Formatters/DateTimeFormatter.cs#L376

Ok, I'll change formatter to allow both string and number.

Gorthog commented 6 years ago

If you can accept double as well it would be awesome - sometimes the format is with a decimal point to include microsecond. for example: 1356295197.028566 this would mean: 2018-4-23 18:2:57.028566