Md. Abdul Alim
Md. Abdul Alim

Reputation: 705

JsonConverter not working as property attribute

I have an object which contains a property with JsonConverter attribute. For data read and write, converter not working. The declared property is

[JsonConverter(typeof(EpochDateTimeConverter))]
public DateTime CreatedOn { get; set; } 

The EpochDateTimeConverter is

public class EpochDateTimeConverter : DateTimeConverterBase
    {
        private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            long millisecondsSinceEpoch;
            if (value is DateTime)
            {
                millisecondsSinceEpoch = Convert.ToInt64((((DateTime)value).ToUniversalTime() - epoch).TotalMilliseconds);
            }
            else
            {
                if (!(value is DateTimeOffset))
                    throw new JsonSerializationException("Expected date object value.");
                millisecondsSinceEpoch = Convert.ToInt64((((DateTimeOffset)value).ToUniversalTime().UtcDateTime - epoch).TotalMilliseconds);
            }
            writer.WriteValue(millisecondsSinceEpoch);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (objectType != typeof(DateTime?) && objectType != typeof(DateTimeOffset?))
                    throw new JsonSerializationException($"Cannot convert null value to {objectType}");

                return null;
            }
            if (reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float)
            {
                var millisecondsSinceEpoch = (long)reader.Value;
                var dateTime = FromUnixTime(millisecondsSinceEpoch);
                if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
                {
                    return dateTime;
                }
                else
                {
                    return new DateTimeOffset(dateTime);
                }
            }
            if (reader.TokenType == JsonToken.Date || reader.TokenType == JsonToken.Float)
            {
                return ConvertToUnixTimestamp(Convert.ToDateTime(reader.Value));
            }
            throw new JsonSerializationException($"Cannot convert to DateTime or DateTimeOffset from token type {reader.TokenType}");
        }
        private static DateTime FromUnixTime(long unixTime)
        {
            try
            {
                return epoch.AddSeconds(unixTime);
            }
            catch(Exception)
            {
                unixTime = unixTime / 1000;
                return epoch.AddSeconds(unixTime);
            }

        }

        public static double ConvertToUnixTimestamp(DateTime date)
        {
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan diff = date.ToUniversalTime() - origin;
            return Math.Floor(diff.TotalSeconds);
        }

    }

I can not get the error. But EpochDateTimeConverter not called automatically. I have not understood what's the wrong. Anyone can help me?

Upvotes: 7

Views: 13252

Answers (3)

Matt
Matt

Reputation: 2290

Make sure to use System.Text.Json.Serialization not Newtonsoft.Json.

Upvotes: 8

Md. Abdul Alim
Md. Abdul Alim

Reputation: 705

After some research I found a mismatch between Enitity and Converter. The JsonConverter were not same of both class. That's why it was not called. After update JsonConverter its working.

Upvotes: -4

Ashiqur Rahman Emran
Ashiqur Rahman Emran

Reputation: 207

This is calling automatically when your JsonConverter is progressing on that time. By default .NET Core API uses to serialize and deserialize the json object using Newtonsoft.Json. Here JsonConverter also exist in the Newtonsoft.Json namespace so in term of using this when you use this JsonConverter static class that time it will call automatically with proper procedure.

JsonConvert.SerializeObject(YourClassWhichContainThePropertyWithYourAttribute);

Also you can check this by calling this function

Upvotes: -2

Related Questions